MyBatisコード例シリーズ-08:MyBatis Generatorプラグインと拡張(中国語の注釈とMapperはDaoとリネーム)


スーパーチャネル:MyBatisコードインスタンスシリーズ-序論
この章は主にMybatis Generatorを使って、どのように拡張最適化するかを記録しています。関連する技術は以下の通りです。-MyBatis Generator:MyBatisコードは自動的にプラグインを生成して、エンティティを生成できます。java、エンティティMapper.javaとエンティティMapper.xml、コメントは英語です。[email protected]:i 24361/mybatis-generator-core.git:オープンソースプラグイン、MyBatis Generatorを拡張し、中国語の注釈を実現し、エンティティEnttity.java、エンティティDao.java、エンティティDao.javaとエンティティDao.xmlという名前に変更しました。generator Config.xml:MyBatis Generatorのプロファイル。ToStringPlugin:MyBatis Generatorのプラグインは、エンティティクラスで自動的にtoString()メソッドを生成する。EqualsHash CodePlugin:MyBatis Generatorのプラグインは、エンティティクラスにhashCode()とEquals()メソッドを自動的に追加します。
1.MyBatis Generator概要
MyBatisフレームを使って開発する時、表を使うたびに、本体類、XMLマッピングファイル、マッピングインターフェースをマニュアルで作成します。これらは重複性の仕事です。MyBatis Generator(MBG)はMybatisのコードジェネレータです。データベース内のテーブルに基づいて、対応するエンティティ類、XMLマッピングファイルとマッピングインターフェースを生成し、大量の時間を節約して、ビジネスロジックに関する機能を開発することができます。もちろん、複数のテーブルが共同でクエリと格納プロセスを行う場合は、まだ手動で処理する必要があります。
2.Mavenを通じてMyBatis Generatorを実行する
2.1.pom.xml
<dependency>
  <groupId>org.mybatis.generatorgroupId>
  <artifactId>mybatis-generator-coreartifactId>
  <version>1.3.6version>
dependency>

<plugins>
...
  <plugin>
    
    <groupId>org.mybatis.generatorgroupId>
    <artifactId>mybatis-generator-maven-pluginartifactId>
    <version>1.3.6version>
    <dependencies>
      
      <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>${mysql.version}version>
      dependency>
    dependencies>
    <configuration>
        
        <configurationFile>src/main/resources/generatorConfig.xmlconfigurationFile>
        
        <overwrite>trueoverwrite>
        
        <verbose>trueverbose>
    configuration>
    
    <executions>
      <execution>
        <id>MyBatis Generatorid>
        <goals>
          <goal>generategoal>
        goals>
      execution>
    executions>
  plugin>
...
plugins>
2.2 MyBatis-generatorプロファイル:generator Config.xml



<generatorConfiguration>
    <properties resource="jdbc.properties"/>
    
    
    
    <context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">

        
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>

        
        
        <commentGenerator>
            
            <property name="suppressAllComments" value="false"/>
            
            <property name="suppressDate" value="true"/>
        commentGenerator>

        
        <jdbcConnection driverClass="${jdbc.driverClassName}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}">
        jdbcConnection>

        
        
        
        <javaModelGenerator targetPackage="pers.hanchao.himybatis.generator.entity" targetProject="src\main\java">
            
            <property name="enableSubPackages" value="true"/>
            
            <property name="trimStrings" value="true" />
        javaModelGenerator>

        
        
        
        <sqlMapGenerator targetPackage="generator"  targetProject="src\main\resources">
            
            <property name="enableSubPackages" value="true"/>
        sqlMapGenerator>

        
        
        
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="pers.hanchao.himybatis.generator.dao" targetProject="src\main\java">
            
            <property name="enableSubPackages" value="true"/>
        javaClientGenerator>

        
        
        
        
        <table schema="exam" tableName="topic">
            
            
            
            <generatedKey column="id" sqlStatement="Mysql"/>
        table>
    context>
generatorConfiguration>
2.3.MyBatis Generatorを実行するIDEAでは、Edit Configurations–をクリックしてMavenの構成を追加します。入力Name–Command Line入力:mybatis-generator:generate–をクリックしてOKをクリックして構成を保存します。
2.4.生成結果
生成ディレクトリは以下の通りです。
src
\---main
    \---java
    |   \---pers
    |       \---hanchao
    |           \---himybatis
    |               \---generator
    |                   \---dao
    |                   |   \---TopicMapper.java
    |                   |---entity
    |                       \---Topic.java
    \---webapp
        \---generator
            \---TopicMapper.xml
コード展示:Topic.javaは最初のフィールドだけを詳細に示し、後続のフィールドと方法は略である。
package pers.hanchao.himybatis.generator.entity;

public class Topic {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column topic.id
     *
     * @mbg.generated
     */
    private Integer id;

    //other field

    //setter getter toString hashCode equals
}
TopicMapper.javaは第一の方法だけを詳細に示しています。
package pers.hanchao.himybatis.generator.dao;

import java.util.List;
import pers.hanchao.himybatis.generator.entity.Topic;

public interface TopicMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table topic
     *
     * @mbg.generated
     */
    int deleteByPrimaryKey(Integer id);

    //int insert(Topic record);
    //Topic selectByPrimaryKey(Integer id);
    //List selectAll();
    //int updateByPrimaryKey(Topic record);
}
TopicMapper.xmlは最初の方法だけを詳細に示しています。後の方法は略です。


<mapper namespace="pers.hanchao.himybatis.generator.dao.TopicMapper">
  <resultMap id="BaseResultMap" type="pers.hanchao.himybatis.generator.entity.Topic">
    
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="title" jdbcType="VARCHAR" property="title" />
    <result column="score" jdbcType="INTEGER" property="score" />
    <result column="answer" jdbcType="VARCHAR" property="answer" />
  resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    
    delete from topic
    where id = #{id,jdbcType=INTEGER}
  delete>
  
mapper>
改善が必要なところ:
  • によって生成されたTopic.javaとTopicMapper.javaのコメントは英語で、特にTopic.javaのフィールドコメントです。実際の開発には友好的ではなく、マニュアルですべての注釈を中国語に変更する必要があります。時間を浪費するだけでなく、間違いやすいです。
  • 私はエンティティのMapperをXxDao.javaまたはXxxxIDAOに名前を変更するのが好きです。XxMapper.javaではなく、手動でAlt+Shift+Xを全部Mavenに変更する必要があります。
  • 3.拡張MyBatis Generator
    以上の理由から、多くの大牛たちはMyBatis Generatorのソースコードを修正したり、新たに実現したりすることによって、さまざまな解決策を提供している。この章では、その中の一つの案だけを詳しく紹介します。XxxxMapperから提供されたものです。https://github.com/li24361/mybatis-generator-core
    3.1.git cloneXxxxDaoプロジェクトをローカルにクローンします。
    git clone git@github.com:li24361/mybatis-generator-core.git
    3.2 jarに打ってローカルRepositoryに包んでください。li24361をジャガーバッグにしてローカル倉庫に保管する。
    cd mybatis-generator-core/
    
    mvn install -Dmaven.test.skip=true
    3.3.pom.xmlを修正する
    注意:mybatis-generator-maven-pluginのバージョン番号は1.3.2です。
    <plugin>
      
      
      
      
      
        
        
          
          
          
        
      
      
      
      <groupId>org.mybatis.generatorgroupId>
      <artifactId>mybatis-generator-maven-pluginartifactId>
      <version>1.3.2version>
      <dependencies>
        
        <dependency>
          <groupId>mysqlgroupId>
          <artifactId>mysql-connector-javaartifactId>
          <version>${mysql.version}version>
        dependency>
        <dependency>
          <groupId>com.haier.hairygroupId>
          <artifactId>mybatis-generator-coreartifactId>
          <version>1.0.1version>
        dependency>
        dependencies>
            <configuration>
            
            <configurationFile>src/main/resources/generatorConfig.xmlconfigurationFile>
            
            <overwrite>trueoverwrite>
            
            <verbose>trueverbose>
         configuration>
      plugin>
    3.4.generator Config.xmlを修正する
    
    
    
    
    <commentGenerator type="org.mybatis.generator.internal.HairyCommentGenerator">
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <property name="suppressAllComments" value="false"/>
        
        <property name="suppressDate" value="true"/>
    commentGenerator>
    3.5.MyBatis Generatorを実行する
    3.6.生成結果
    生成ディレクトリは以下の通りです。
    src
    \---main
        \---java
        |   \---pers
        |       \---hanchao
        |           \---himybatis
        |               \---generator
        |                   \---dao
        |                   |   \---TopicDao.java
        |                   |---entity
        |                       \---TopicEntity.java
        \---webapp
            \---generator
                \---TopicDao.xml
    コード展示:TopicEnttity.javaは最初のフィールドだけを詳細に示しています。後のフィールドと方法は略です。
    package pers.hanchao.himybatis.generator.entity;
    
    public class TopicEntity {
        /**
         * 
    
         *   
         *     : topic.id
         * 
    */
    prvate Integer id
    //other fields
    //setter getter toString hash Code equals
    )
    TopicDao.javaは の を に すだけで、 の は である。
    package pers.hanchao.himybatis.generator.dao;
    
    import java.util.List;
    import pers.hanchao.himybatis.generator.entity.TopicEntity;
    
    public interface TopicDao {
        /**
         *             
         *
         * @param id
         */
        int deleteByPrimaryKey(Integer id);
    
        //int insert(Topic record);
        //Topic selectByPrimaryKey(Integer id);
        //List selectAll();
        //int updateByPrimaryKey(Topic record);
    }
    TopicDao.xmlの は と じで、もはや しない。
    まとめ:mybatis-generator-coreによって されるhttps://github.com/li24361/mybatis-generator-core かに の を しました。
  • は、 な の
  • を する。
  • は の にもっと しています。TopicEnttity.java、TopicDao.java、TopicDao.xml
  • 4. コードの をテストします。
    mybatis-generator-coreにより、 されたTopicEnttity.java、TopicDao.java、TopicDao.xmlのユーザビリティテストを します。
    TopicApp.java
    package pers.hanchao.himybatis.generator;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.apache.log4j.Logger;
    import pers.hanchao.himybatis.generator.dao.TopicDao;
    import pers.hanchao.himybatis.generator.entity.TopicEntity;
    
    import java.io.IOException;
    import java.io.Reader;
    
    /**
     * 

    MyBatis Generator

    * @author hanchao 2018/2/4 10:45 **/
    public class TopicApp { /** */ private static final Logger LOGGER = Logger.getLogger(TopicApp.class); /** */ private static Reader reader; /** */ private static SqlSessionFactory sqlSessionFactory; static { try { // reader = Resources.getResourceAsReader("mybatis-config-generator.xml"); // sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } /** *

    MyBatis Generator

    * @author hanchao 2018/2/4 10:46 **/
    public static void main(String[] args) { // SqlSession sqlSession = sqlSessionFactory.openSession(); try { // Dao TopicDao topicDao = sqlSession.getMapper(TopicDao.class); // LOGGER.info(" "); LOGGER.info(topicDao.selectAll()); // , System.out.println(); LOGGER.info(" "); TopicEntity newTopic = new TopicEntity(); newTopic.setId(100); newTopic.setTitle(" "); newTopic.setScore(200); newTopic.setAnswer(" "); topicDao.insert(newTopic); LOGGER.info(topicDao.selectAll()); // System.out.println(); LOGGER.info(" "); LOGGER.info(topicDao.selectByPrimaryKey(1)); // , System.out.println(); LOGGER.info(" "); newTopic = new TopicEntity(); newTopic.setId(1); newTopic.setTitle(" "); newTopic.setScore(1000); newTopic.setAnswer(" "); topicDao.updateByPrimaryKey(newTopic); LOGGER.info(topicDao.selectByPrimaryKey(1)); // , System.out.println(); LOGGER.info(" , "); topicDao.deleteByPrimaryKey(1); LOGGER.info(topicDao.selectByPrimaryKey(1)); // sqlSession.commit(); }catch (Exception e){ e.printStackTrace(); LOGGER.info("error!"); sqlSession.rollback(); }finally { sqlSession.close(); } } }
    :
    2018-02-04 16:38:59 INFO  TopicApp:49 -     
    2018-02-04 16:38:59 DEBUG JdbcTransaction:54 - Opening JDBC Connection
    2018-02-04 16:39:00 DEBUG PooledDataSource:54 - Created connection 1316864772.
    2018-02-04 16:39:00 DEBUG JdbcTransaction:54 - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4e7dc304]
    2018-02-04 16:39:00 DEBUG selectAll:54 - ==>  Preparing: select id, title, score, answer from topic 
    2018-02-04 16:39:00 DEBUG selectAll:54 - ==> Parameters: 
    2018-02-04 16:39:00 DEBUG selectAll:54 - <==      Total: 2
    2018-02-04 16:39:00 INFO  TopicApp:50 - [TopicEntity [Hash = -756562783, id=1, title=   1111, score=1001111, answer=   111], TopicEntity [Hash = 1936880702, id=99999, title=  1, score=100, answer=   ?]]
    
    2018-02-04 16:39:00 INFO  TopicApp:53 -     
    2018-02-04 16:39:00 DEBUG insert!selectKey:54 - ==>  Preparing: SELECT LAST_INSERT_ID() 
    2018-02-04 16:39:00 DEBUG insert!selectKey:54 - ==> Parameters: 
    2018-02-04 16:39:00 DEBUG insert!selectKey:54 - <==      Total: 1
    2018-02-04 16:39:00 DEBUG insert:54 - ==>  Preparing: insert into topic (id, title, score, answer) values (?, ?, ?, ?) 
    2018-02-04 16:39:00 DEBUG insert:54 - ==> Parameters: 0(Integer),      (String), 200(Integer),      (String)
    2018-02-04 16:39:00 DEBUG insert:54 - <==    Updates: 1
    2018-02-04 16:39:00 DEBUG selectAll:54 - ==>  Preparing: select id, title, score, answer from topic 
    2018-02-04 16:39:00 DEBUG selectAll:54 - ==> Parameters: 
    2018-02-04 16:39:00 DEBUG selectAll:54 - <==      Total: 3
    2018-02-04 16:39:00 INFO  TopicApp:60 - [TopicEntity [Hash = -756562783, id=1, title=   1111, score=1001111, answer=   111], TopicEntity [Hash = 1936880702, id=99999, title=  1, score=100, answer=   ?], TopicEntity [Hash = -1744254903, id=100001, title=     , score=200, answer=     ]]
    
    2018-02-04 16:39:00 INFO  TopicApp:63 -     
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==>  Preparing: select id, title, score, answer from topic where id = ? 
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Parameters: 1(Integer)
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - <==      Total: 1
    2018-02-04 16:39:00 INFO  TopicApp:64 - TopicEntity [Hash = -756562783, id=1, title=   1111, score=1001111, answer=   111]
    
    2018-02-04 16:39:00 INFO  TopicApp:67 -     
    2018-02-04 16:39:00 DEBUG updateByPrimaryKey:54 - ==>  Preparing: update topic set title = ?, score = ?, answer = ? where id = ? 
    2018-02-04 16:39:00 DEBUG updateByPrimaryKey:54 - ==> Parameters:      (String), 1000(Integer),      (String), 1(Integer)
    2018-02-04 16:39:00 DEBUG updateByPrimaryKey:54 - <==    Updates: 1
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==>  Preparing: select id, title, score, answer from topic where id = ? 
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Parameters: 1(Integer)
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - <==      Total: 1
    2018-02-04 16:39:00 INFO  TopicApp:74 - TopicEntity [Hash = 1122539663, id=1, title=     , score=1000, answer=     ]
    
    2018-02-04 16:39:00 INFO  TopicApp:77 -2018-02-04 16:39:00 DEBUG deleteByPrimaryKey:54 - ==>  Preparing: delete from topic where id = ? 
    2018-02-04 16:39:00 DEBUG deleteByPrimaryKey:54 - ==> Parameters: 1(Integer)
    2018-02-04 16:39:00 DEBUG deleteByPrimaryKey:54 - <==    Updates: 1
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==>  Preparing: select id, title, score, answer from topic where id = ? 
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - ==> Parameters: 1(Integer)
    2018-02-04 16:39:00 DEBUG selectByPrimaryKey:54 - <==      Total: 0
    2018-02-04 16:39:00 INFO  TopicApp:79 - 
    5. とより くの
  • ネット
  • MyBatis のコード Generator
  • https://github.com/li24361/mybatis-generator-core
  • mybatis-generatorコード ソリューションデータベースの
  • MyBatis Generator
  • な :
  • mybatis-generator-gui:mybatis generatorに づいて、インタフェースツール
  • を しました。
  • MyBatis Generatorプラグインの プラグインパッケージ:MySQL ページプラグイン、 データプラグインの など