Mybatis入門はこれを見れば十分です。

28075 ワード

MyBatisとは何ですか
MyBatisはapacheのオープンソースプロジェクトiBatisで、2010年にこのプロジェクトはapphe software foundationからgoogle codeに移行し、MyBatisと改名しました。は、Javaベースの耐久層フレームです。
なぜ私たちはMybatisを使いますか?
Mybatis、HibernateはいずれもORMの実現フレームであり、JDBCへのパッケージです。
今まで、私たちはもう長い間、いくつかの技術を学びました。
  • ヒベルナタ
  • jdbc
  • SprigDAO
  • なぜ私たちはMybatisを勉強しますか?今はMybatisが業界で活躍していますが、なぜ彼はそんなに怒ることができますか?
    Hbernateは古いフレームです。彼を使ったことがある学生はみんな知っています。使えば、とても快適です。sqlコードは何も書かなくてもいいです。しかし、複雑な業務を扱う時、柔軟性が悪くて、複雑なHQLは難しいです。例えば、複数の表で調べたHQL文などです。
    JDBCは分かりやすいです。いくつかの決まった手順については開発が面倒くさいです。何でも自分でやります。
    SprigDAOとは、JDBCのパッケージのことで、dbutilsのように特別な色が出ていないところです。
    私たちはMybatisがjdbcとHybernateのバランスの一つだと考えてもいいです。今業界はこのフレームを使っていますから、私たちも勉強しないわけにはいきません。
    Mybatis快速入門
    実は私たちはもうヒップホップを習っています。Mybatis入門にはとても似ています。だから簡単に基本的な開発ができます。
    開発パッケージをインポート
    Mybatis開発パッケージの導入
  • mybatis-31.11.jar
  • commons-loging-1.11.jar
  • log 4 j-1.2.16.jar
  • cglib-23.22.jar
  • asm-33.1.jar
  • mysql/oracle開発パッケージを導入します。
  • mysql-connector-java-5.7-bin.jar
  • Oracle 11 g 11.2..1.0 JDBC_o jdbc 6.jar
  • テストの準備
    テーブルを作成
    
    create table students(
      id  int(5) primary key,
      name varchar(10),
      sal double(8,2)
    );
    作成エンティティ:
    
    /**
     * Created by ozc on 2017/7/21.
     */
    
    public class Student {
        private Integer id;
        private String name;
        private Double sal;
    
        public Student() {
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Double getSal() {
            return sal;
        }
    
        public void setSal(Double sal) {
            this.sal = sal;
        }
    }
    
    mybatisプロファイルを作成します。
    mybatisのプロファイルを作成して、データベースの情報を設定します。データベースは複数配置できますが、デフォルトは一つしか使えません。
    
    
    
    
    
        
        
        
        
    
        
        
            
            
                
                
                
                
                    
                    
                    
                    
                    
                
            
            
            
            
            
                
                
                
                
                    
                    
                    
                    
                    
                
            
        
        
        
    
    ツール類を作成して接続を取得したかどうかをテストします。
    MybatisのAPIを使ってツールクラスを作成し、mybatisプロファイルとデータベースの情報を配置することで、Connectionオブジェクトを得る。
    
    package cn.itcast.javaee.mybatis.util;
    
    import java.io.IOException;
    import java.io.Reader;
    import java.sql.Connection;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    /**
     *    
     * @author AdminTC
     */
    public class MybatisUtil {
        private static ThreadLocal threadLocal = new ThreadLocal();
        private static SqlSessionFactory sqlSessionFactory;
        /**
         *     src/mybatis.xml    
         */
        static{
            try {
                Reader reader = Resources.getResourceAsReader("mybatis.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        /**
         *       new     
         */
        private MybatisUtil(){}
        /**
         *   SqlSession
         */
        public static SqlSession getSqlSession(){
            //        SqlSession  
            SqlSession sqlSession = threadLocal.get();
            //  SqlSession    
            if(sqlSession == null){
                // SqlSessionFactory      ,  SqlSession  
                sqlSession = sqlSessionFactory.openSession();
                // SqlSession            
                threadLocal.set(sqlSession);
            }
            //  SqlSession  
            return sqlSession;
        }
        /**
         *   SqlSession       
         */
        public static void closeSqlSession(){
            //        SqlSession  
            SqlSession sqlSession = threadLocal.get();
            //  SqlSession    
            if(sqlSession != null){
                //  SqlSession  
                sqlSession.close();
                //       SqlSession     ,    GC    
                threadLocal.remove();
            }
        }   
        /**
         *   
         */
        public static void main(String[] args) {
            Connection conn = MybatisUtil.getSqlSession().getConnection();
            System.out.println(conn!=null?"    ":"    ");
        }
    }
    
    
    
    
    エンティティとマッピング関係ファイルを作成します。
    設定エンティティとテーブルのマッピング関係
    
    
    
    
    
     
        
        
        
                                     
            
            
            
        
    
    
    今はMybatisのプロファイルとテーブルとエンティティの前のマッピングファイルがありますので、プロファイルとマッピングファイルを関連付ける必要があります。
    
        
            
        
    テストクラスでは、私たちは接続を得ることができます。
    DAOを作成
    
    public class StudentDao {
    
    
        public void add(Student student) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            sqlSession.insert();
        }
    
        public static void main(String[] args) throws Exception {
    
            StudentDao studentDao = new StudentDao();
    
            Student student = new Student(1, "zhongfucheng", 10000D);
            studentDao.add(student);
    
        }
    }
    
    これまでのところ、私たちのエンティティとテーブルのマッピングファイルは、エンティティ属性とテーブルのフィールドとの関係だけをマッピングしました。
    私たちはヒップホップの中にデータを挿入したいなら、セーブ方法を呼べばいいです。Hibernateは自動化でデータベースの違いを遮りました。Mybatisは自分でSQLコードを手動で作成する必要があります。
    SQLコードはどこに書いてありますか?明らかに、私たちはフレームとしてSQLをプログラムに書くことができません。私たちはエンティティとテーブルのマッピングファイルに書いています。
    Mybatisエンティティとテーブルのマッピングファイルにinsertタグ「SQLコードセグメント」を提供しています。
    
        // JDBC       ?      ,  Mybatis ,     #{}     
        //parameterType            
        //#{}        Student   get  
    
        
    
            INSERT INTO ZHONGFUCHENG.STUDENTS (ID, NAME, SAL) VALUES (#{id},#{name},#{sal});
        
    
    プログラムでマッピングファイルのSQLコードセグメントを呼び出します。
    
        public void add(Student student) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                sqlSession.insert("StudentID.add", student);
                sqlSession.commit();
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
    注意すべきことは、Mybatisの事務はデフォルトでオープンしていますので、操作が完了したら、マニュアルで事務を提出する必要があります。
    Mybatisワークフロー
  • MybatisマッピングファイルをReaderオブジェクトで読み出す
  • Sql Session FactoryBuiderオブジェクトを介してSql Session Factoryオブジェクト
  • を作成する。
  • は、現在のスレッドのSQLSession
  • を取得する。
  • 事務デフォルトオープン
  • は、マッピングファイルの動作番号をSQLSessionで読み、SQL文
  • を読み出す。
  • 提出事務
  • リソースを閉じる
  • CRUD操作を完了しました
    私たちは上で簡単にMybatisの使い方と作業の流れを分かりました。今回はMybatisを使ってCRUDの操作を完成し、Mybatisの開発手順と詳細を再強化します。
    クラス間の構造
    学生を増やす
    設定ファイル
    
    
    
    
        
        
    
        
        
            
            
                
                
                
                
                    
                    
                    
                    
                    
                
            
    
            
            
            
                
                
                
                
                    
                    
                    
                    
                    
                
            
        
        
            
        
    
    
    
    マップファイル
    
    
        
        
        
            
            
            
            
        
    
        
            INSERT INTO ZHONGFUCHENG.STUDENTS (ID, NAME, SAL) VALUES (#{id},#{name},#{sal});
        
    
    
    
    
    データの挿入
    
    public class StudentDao {
    
        public void add(Student student) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                sqlSession.insert("StudentID.add", student);
                sqlSession.commit();
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            Student student = new Student(3, "zhong3", 10000D);
            studentDao.add(student);
        }
    }
    
    IDに基づいてデータを照会する
    selectタグを追加
    
        
        
    
    検索結果はStudentオブジェクトです。SelectOneメソッドを呼び出します。
    
        public Student findById(int id) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                return sqlSession.selectOne("StudentID.findById",id);
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            Student student = studentDao.findById(1);
            System.out.println(student.getName());
    
        }
    すべてのデータを検索
    
        
        
    私たちが調べた結果は単なる対象ではなく、SelectListという方法を使っています。
      public List findAll() throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                return sqlSession.selectList("StudentID.findAll");
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            List students = studentDao.findAll();
            System.out.println(students.size());
    
        }
    idによる削除
    
        
        
            DELETE FROM STUDENTS WHERE id=#{id};
    
        
    
    deleteメソッドを呼び出して削除します。
    
    
        public void delete(int id ) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                sqlSession.delete("StudentID.delete", id);
                sqlSession.commit();
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            studentDao.delete(1);
    
        }
    変更
    
        
        
    
            update students set name=#{name},sal=#{sal} where id=#{id};
    
        
    対応するオブジェクトを検索して、変更します。
    
    
        public void update(Student student ) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                sqlSession.update("StudentID.update", student);
                sqlSession.commit();
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            Student student = studentDao.findById(2);
            student.setName("fucheng");
            student.setSal(2000D);
            studentDao.update(student);
    
        }
    
    
    細かいところ
    
         
    
    Mybatis改ページ
    改ページはとても実用的な技術点です。私たちもMybatisを使って、どのように改ページされているのかを勉強してみます。
    私たちの改ページは複数のパラメータが必要です。私たちの前の例のように一つのパラメータだけが必要ではありません。複数のパラメータを受信する必要がある場合は、Mapセットを使用して積載します。
    
        public List  pagination(int start ,int end) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
    
    
                /**
                 *             ,        Object    
                 *       Map          
                 */
                Map map = new HashMap();
                map.put("start", start);
                map.put("end", end);
                return sqlSession.selectList("StudentID.pagination", map);
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            List students = studentDao.pagination(0, 3);
            for (Student student : students) {
    
                System.out.println(student.getId());
    
            }
    
        }
    エンティティとテーブルマッピングファイルでは、受信したパラメータがmapセットです。
    
    
        
        
    
    ダイナミックSQL
    ダイナミックSQLとは?以前書いたSSHプロジェクトの中で、いろいろな条件の照会があります。
    私たちが最初に作った時は、Controllerの中でSQLに条件があるかどうかを判断する必要がありました。SQL文はつなぎ合わせが必要ですから。そうすると、間違いやすいです。
    下記のコードは、複数の条件があれば、つなぎ合わせて間違いやすいです。
    
      public String listUI() {
    
            //    
            String hql = "FROM Info i ";
            List objectList  = new ArrayList<>();
    
            //  info   null          。  info  ,       。
            if (info != null) {
                if (StringUtils.isNotBlank(info.getTitle())) {
                    hql += "where i.title like ?";
                    objectList.add("%" + info.getTitle() + "%");
                }
            }
            infoList = infoServiceImpl.findObjects(hql,objectList);
            ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);
            return "listUI";
        }
    その後、私達はこのようによくないと思いました。そこで、専門的に調査助手類を書きました。
    
    package zhongfucheng.core.utils;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by ozc on 2017/6/7.
     */
    public class QueryHelper {
    
        private String fromClause = "";
        private String whereClause = "";
        private String orderbyClause = "";
        private List objectList;
    
        public static String ORDER_BY_ASC = "asc";
        public static String ORDER_BY_DESC = "desc";
    
    
    
        //FROM       
        /**
         *   FROM  ,        
         * @param aClass          
         * @param alias    
         */
        public QueryHelper(Class aClass, String alias) {
            fromClause = "  FROM " + aClass.getSimpleName() + "  " + alias;
        }
        //WHERE          , WHERE        
        /**
         *   WHERE  
         * @param condition
         * @param objects
         * @return
         */
        public QueryHelper addCondition(String condition, Object... objects) {
            //        ,        WHERE    
            if (whereClause.length() > 0) {
                whereClause += " AND  " + condition;
            } else {
                whereClause += " WHERE" + condition;
            }
            //          ,?        
            if (objects == null) {
                objectList = new ArrayList<>();
            }
    
            for (Object object : objects) {
                objectList.add(object);
            }
    
            return this;
        }
        /**
         *
         * @param property       
         * @param order        
         * @return
         */
        public QueryHelper orderBy(String property, String order) {
    
            //        ,        ORDER    
            if (orderbyClause.length() > 0) {
                orderbyClause += " ,  " + property +"   " + order;
            } else {
                orderbyClause += "  ORDER BY " + property+"   " + order;
            }
            return this;
        }
    
        /**
         *   HQL  
         */
        public String returnHQL() {
            return fromClause + whereClause + orderbyClause;
        }
    
        /**
         *       
         * @return
         */
        public List getObjectList() {
            return objectList;
        }
    }
    こうすれば、私たちは自分でマニュアルで接続しなくてもいいです。私たちの検索助手類をつなぎ合わせてください。
    もし私たちがMybatisを使うなら、アシスタント類を調べなくてもいいです。Mybatis内部にダイナミックSQLの機能があるからです。
    動的クエリ
    
        
        
        
    
        
    9000円未満の人を調べました。
    
       public List findByCondition(String name,Double sal) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                /**
                 *             ,        Object    
                 *       Map          
                 */
                Map map = new HashMap();
                map.put("name", name);
                map.put("sal", sal);
                return sqlSession.selectList("StudentID.findByCondition", map);
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            List students = studentDao.findByCondition(null,9000D);
            for (Student student : students) {
                System.out.println(student.getId() + "---" + student.getName() + "----" + student.getSal());
            }
    
    
        }
    ダイナミック更新
    
        
        
        
    
            update students
            
                
                     name = #{name},
                
                
                     sal = #{sal},
                
            
            where id = #{id}
        
    3つの更新フィールドを与えます。
    
        public void updateByConditions(int id,String name,Double sal) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                /**
                 *             ,        Object    
                 *       Map          
                 */
                Map map = new HashMap();
                map.put("id", id);
                map.put("name", name);
                map.put("sal", sal);
                sqlSession.update("StudentID.updateByConditions", map);
                sqlSession.commit();
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
    
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            studentDao.updateByConditions(2,"haha",500D);
    
        }
    動的削除
    以前は私たちはJDBCを使っても、Hibernateを使っても、大量に削除したい時は、いつも循環的に削除します。今使っているのはMybatisです。SQL文は自分で書きました。だから私達は下記のSQLを書いて削除してもいいです。
    
    delete from students where id in (?,?,?,?);
    私達のMybatisはまた動態SQLを支持して、だから削除してとても便利になりました!
    
        
    
            
            delete from students where id in
             
                 #{ids}
             
    
        
    削除番号は2、3、4のレコードです。
        public void deleteByConditions(int... ids) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                /**
                 *             ,        Object    
                 *       Map          
                 */
                sqlSession.delete("StudentID.deleteByConditions", ids);
                sqlSession.commit();
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
    
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            studentDao.deleteByConditions(2,3,4);
    
        }
    
    動的挿入
    動的に挿入したいなら、他のDMM文より少し複雑です。二つの部分が不確定です。普通のSQL文はこうです。
    
    insert into student(id,name,sal) values(?,?,?)
    
    SQLコードブロックは前のように自動的に余分なカンマを取り除くことができません。だから私達はtrimラベルを使って自分で手動で取り除く必要があります。
    insertSQL文を書くときは、括弧を書くのを忘れないでください。
    
        
        
            
                
                    id,
                
    
                
                    name,
                
    
                
                    sal,
                
            
        
    
        
            
                
                    #{id},
                
    
                
                    #{name},
                
    
                
                    #{sal},
                
            
        
        
        
        
            insert into students () values
            ()
    
        
    三つの異なる内容のデータをテストします。
    
        public void insertByConditions(Student student) throws Exception {
            //      
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            try{
                //         .SQL   ID,              SQL
                sqlSession.insert("StudentID.insertByConditions", student);
                sqlSession.commit();
            }catch(Exception e){
                e.printStackTrace();
                sqlSession.rollback();
                throw e;
            }finally{
                MybatisUtil.closeSqlSession();
            }
        }
    
        public static void main(String[] args) throws Exception {
            StudentDao studentDao = new StudentDao();
            studentDao.insertByConditions(new Student(55, null, null));//name sal  
    
            studentDao.insertByConditions(new Student(66, "haxi", null));//sal  
            studentDao.insertByConditions(new Student(77, null, 3999d));//name  
    
    
        }
    締め括りをつける
  • Mybatisの準備はHybernateと同じです。全体構成ファイル、マッピングファイルが必要です。
  • MybatisのSQLSessionツール類は、スレッド内のSessionをThreadLocalを使用して管理しています。
  • Mybatisのビジネスはデフォルトではオープンしています。手動で事務を提出する必要があります。
  • MybatisのSQL文は手書きが必要で、プログラムでファイルの名前空間をマッピングします。sql文のidで呼び出します。
  • はMybatisの中で、添削と検索は自分でSQL文を書く必要があります。そしてプログラムの中で呼び出してもいいです。SQLは私達が自分で書いたので、ヒベルナに対して柔軟です。
  • に複数のパラメータが入る必要があるならば、マッピングファイルでMapで受信するのが一般的である。
  • 私たちは開発において常に条件照会を利用していますので、以前はSQLに対する接続を完了するためにクエリーアシスタントを使っていました。Mybatisなら、SQLコードは自分で書きます。
  • Mybatisもいくつかの判断タグをサポートしています。そこで、これらのラベルを使って動的CRUDの操作ができます。
  • 注意すべきなのは、私達のsqlセグメントコードは私達自身で手動で分割し、番号が必要です。
  • 文章に間違いがあれば指摘を歓迎し、お互いに交流します。WeChatで技術記事を読むことに慣れています。より多くのJava資源を得ようとする学生は、WeChat公式アカウントに注目してください。