mybatisシロへの入門ガイド


一、myabtisとは
公式リンク:www.mybatis.org/mybatis-3/z...
MyBatisは、SQLのカスタマイズ、ストレージ・プロシージャ、高度なマッピングをサポートする優れた永続層フレームワークです.MyBatisは、ほとんどのJDBCコードと手動でパラメータを設定し、結果セットを取得することを回避します.MyBatisは、単純なXMLまたは注釈を使用してオリジナル情報を構成およびマッピングし、インタフェースとJavaのPOJOs(Plain Old Java Objects、通常のJavaオブジェクト)をデータベース内のレコードにマッピングすることができます.
要するにmybatisはデータ永続層フレームワークです(ORMフレームワークではないことを覚えています).
二、mybatisを使用してデータベースを操作する
  • mybatis
  • を導入
            
                org.mybatis
                mybatis
                3.4.5
            
    

    すべてのpomファイル構成:
    "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        4.0.0
        source.code
        mybatis
        war
        1.0-SNAPSHOT
        mybatis Maven Webapp
        http://maven.apache.org
        
            
                junit
                junit
                4.12
                test
            
            
                org.mybatis
                mybatis
                3.4.5
            
            
                mysql
                mysql-connector-java
                5.1.38
            
            
                log4j
                log4j
                1.2.17
            
            
                org.slf4j
                slf4j-api
                1.7.7
            
            
                org.slf4j
                slf4j-log4j12
                1.7.7
            
        
        
            mybatis
        
    
    
    
  • mybatisプロファイルを追加します.マッピングファイルプロファイルの名前はmybatis.xml、マッピングファイルの名前はarticle.xml
  • です.
    mybatis.xmlファイル:
    "1.0" encoding="UTF-8" ?>
    span class="hljs-string">"-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    
        "config.properties">
            "username" value="root"/>
            "password" value="root"/>
        
        
        <typeAliases>
            <typeAlias type="com.mybatis.demo.entity.Article" alias="Article"/>
        typeAliases>
    
        "development">
            "development">
                type="JDBC">
                type="POOLED">
                    "driver" value="${driver}"/>
                    "url" value="${url}"/>
                    "username" value="${username}"/>
                    "password" value="${password}"/>
                
            
        
        
            "article.xml">
        
    
    
    

    分析:mybatis.xmlファイルはデータベース、マッピングファイルなどの情報を構成します.(1)propertiesラベルはいくつかの基本属性値を構成し、中にいくつかの定数を配置して他のラベル参照を便利にすることができる.propertiesラベルは、resourceプロパティを使用してプロファイルのパスを指定できます.ここでは、読み出しプロファイルが先に読み込まれ、プロファイルが存在する場合はプロファイルのキー値ペアの内容が取得され、propertiesのサブラベルpropertyにキー値ペアが構成されているプロファイルと読み出したプロファイルの同じキーの内容がある場合は、キー値ペアのプロファイルの内容が上書きされます.すなわち、優先順位は、propertyラベル>proertiesファイルです.(2)environmentsラベル構成データベースのいくつかの環境、例えばデータソース、トランザクション管理(3)mappersラベルマッピングファイルのパスを構成複数のmappersファイル(4)を構成し、さらに多くのラベルと属性をこの文章では分析せずに、後続の文章で詳細に分析する
    config.propertiesファイルの内容
    url=jdbc:mysql://localhost:3306/my_test_db?characterEncoding=UTF-8&useSSL=false
    driver=com.mysql.jdbc.Driver
    

    article.xmlファイル
    "1.0" encoding="UTF-8" ?>
    span class="hljs-string">"-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    "com.mybatis.demo.mapper.ArticleMapper">
    
        
    
    
        "insert" parameterType="Article">
            INSERT INTO article (title, content) VALUES (#{title}, #{content})
        
    
        "update" parameterType="Article">
            UPDATE article SET title = #{title} WHERE id = #{id}
        
    
        "delete" parameterType="int">
            DELETE FROM article WHERE id = #{id}
        
    
    
    
  • エンティティークラス
  • を作成する
    Article.java
    public class Article {
    
        private Integer id;
        private String title;
        private String content;
    
        public String getTitle() {
            return title;
        }
    
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    }
    
    
  • Mapperクラス
  • を作成する
    ArticleMapper.java
    @Mapper
    public interface ArticleMapper {
    
        /**
         *     
         *
         * @param article
         * @return
         */
        boolean insert(Article article);
    
        /**
         *       
         *
         * @param id   id
         * @return
         */
        Article selectOne(int id);
    
        /**
         *     
         *
         * @param article
         * @return
         */
        int update(Article article);
    
        /**
         *     
         *
         * @param id
         * @return
         */
        int delete(int id);
    
    }
    
    
  • テストクラス
  • を作成
    ArticleMapperTest.java
    public class ArticleMapperTest {
    
        private SqlSessionFactory sqlSessionFactory;
        private ArticleMapper mapper;
        private SqlSession sqlSession;
    
        @Before
        public void setUp() throws IOException {
            String mybatisCfg = "mybatis.xml";
            InputStream in = Resources.getResourceAsStream(mybatisCfg);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            sqlSession = sqlSessionFactory.openSession();
            mapper = sqlSession.getMapper(ArticleMapper.class);
        }
    
        @After
        public void close() {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    
        @Test
        public void testDelete() {
            int count = mapper.delete(3);
            sqlSession.commit();
            System.out.println(count);
        }
    
    
        @Test
        public void testUpdate() {
            Article article = new Article();
            article.setId(3);
            article.setTitle("source code");
            int count = mapper.update(article);
            sqlSession.commit();
            System.out.println(count);
        }
    
    
        @Test
        public void testSelectOne() {
            Article article = mapper.selectOne(1);
            System.out.println("title:" + article.getTitle() + " " + "content:" + article.getContent());
            sqlSession.close();
        }
    
        @Test
        public void testInsertV1() {
            Article article = new Article();
            article.setTitle("    ");
            article.setContent("      ");
            int count = sqlSession.insert("com.mybatis.demo.mapper.ArticleMapper.insert", article);
            sqlSession.commit();
            sqlSession.close();
            System.out.println(count);
        }
    
        @Test
        public void testInsertV2() {
            Article article = new Article();
            article.setTitle("v2-  ");
            article.setContent("v2-    ");
            boolean flag = mapper.insert(article);
            sqlSession.commit();
            sqlSession.close();
            System.out.println(flag);
        }
    }
    
    

    上のテストコードを順に分析します.まず、テスト例を実行する前に何をしたかを見てみましょう.
        @Before
        public void setUp() throws IOException {
            String mybatisCfg = "mybatis.xml";
            InputStream in = Resources.getResourceAsStream(mybatisCfg);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            sqlSession = sqlSessionFactory.openSession();
            mapper = sqlSession.getMapper(ArticleMapper.class);
        }
    
    InputStream in = Resources.getResourceAsStream(mybatisCfg);でプロファイルをロードし、SqlSessionFactoryを作成し、SqlSessionFactoryでSqlSessionを取得します.mybatisでは、SqlSessionインスタンスはデータベース接続を表し、SqlSessionはSqlSessionFactoryによって取得されます.アプリケーション全体で実行するには、1つのSqlSessionFactoryインスタンスしか必要ありませんが、複数のSqlSessionインスタンスを持つことができます.SqlSessionはスレッドが安全ではないので、メソッドレベルでSqlSessionを使用し、使用が完了したら接続を閉じて、リソースの浪費を避けたほうがいいです.
    次に、データを追加する操作を見てみましょう.
        @Test
        public void testInsertV1() {
            Article article = new Article();
            article.setTitle("    ");
            article.setContent("      ");
            int count = sqlSession.insert("com.mybatis.demo.mapper.ArticleMapper.insert", article);
            sqlSession.commit();
            sqlSession.close();
            System.out.println(count);
        }
    

    (1)我々はSqlSessionによってデータベースを操作し,insertメソッドを呼び出し,1番目のパラメータは対応するマッピングクラスのメソッドの全パスを指定し,2番目のパラメータは追加されたデータである.(2)insertメソッドを実行するとmybatisはメソッドの最初のパラメータで指定した全パスに基づいて対応するsqlマッピング構成を検索する.ここでmybatisは、「com.mybatis.demo.mapper.ArticleMapper.insert」に基づいて、対応するマッピングファイルに対応するsqlマッピング構成を検索します.mybatisのマッピングファイルの各sqlマッピング構成には一意のidが対応しており、(マッピングファイルのネーミングスペース+sqlマッピング構成のid属性値)のハッシュ値と簡単に理解できる.そこでmabtisはネーミングスペースが「com.mybatis.demo.mapper.ArticleMapper」で、sqlマッピング構成id属性値が「insert」のsqlマッピング構成を見つけた.
    データベースを操作する際には,SqlSessionを直接操作するのではなく,SqlSessionによってMapperを取得し,Mapperによってデータベースを操作することができる.
        @Test
        public void testInsertV2() {
            Article article = new Article();
            article.setTitle("v2-  ");
            article.setContent("v2-    ");
            boolean flag = mapper.insert(article);
            sqlSession.commit();
            sqlSession.close();
            System.out.println(flag);
        }
    

    原理は,SqlSessionを用いてデータベースを直接操作するのと同様に,MapperとSqlSessionを関連付けるだけであり,Mapperのinsertメソッドを実行する際にも,対応するsqlマッピング構成を探す.ただし,この場合はMapperのフルパス名+実行するメソッド名(パラメータを用いない)を用いてsqlマッピング構成を検索する.したがって,我々のマッピングファイルのネーミングスペースに必要なMapperのフルパス名,sqlマッピング構成のid属性値はMapperのメソッドと同名でなければならない.
    データベース・レコードを取得する操作をもう一度見てみましょう.
        @Test
        public void testSelectOne() {
            Article article = mapper.selectOne(1);
            System.out.println("title:" + article.getTitle() + " " + "content:" + article.getContent());
            sqlSession.close();
        }
    

    MapperのselectOneメソッドを実行する場合、前のプロセスは、1つのデータを挿入するのと同じように、プロファイルを検索し、sqlを解析し、sqlを実行します.ただし、sqlを実行するとmybatisは結果をマッピングし、マッピング結果セットを返します.
    削除は更新操作の原理と同じで、多くの分析にすぎません.プロファイルとマッピングファイルのディレクトリを図に示します.
    広告時間は無視できます.
    深夜程猿は微信が最近公众号のアイコンを修正することを许さないため、公众号は最近运営されているので、まだアイコンを设置していません.