天天看點

Data Access 之 MyBatis(七)- MBG & PageHelper

一、MyBatis Generator

MyBatis逆向工程是指可以根據資料庫表的分析逆向生成Entity實體類、Mapper接口以及Mapper XML等類和XML檔案,逆向工程會用到MyBatis官方提供的代碼生成器即MyBatis Generator

1.1 工程搭建

建立項目mybatis-mbg-pagehelper,項目依賴與QA 由淺入深持久層架構(七)- MyBatis Cache中的mybatis-cache項目的依賴一緻,這裡不再重複。但是需要新增加如上所述的Mybatis Generator Core的依賴

<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.4.0</version>
</dependency>           

複制

MyBatis Generator XML Configuration File 示例,拷貝内容放到resource目錄下的generatorConfig.xml檔案中。

主要修改

  • 資料庫連接配接資訊配置
  • 生成的Entity實體類位置配置
  • 生成的Mapper XML檔案存放位置配置
  • 生成的Mapper接口位置配置
  • 映射的Table配置 ```xml
<context id="test" targetRuntime="MyBatis3" >
    <!--修改資料庫連接配接配置-->
    <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                    connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;amp;characterEncoding=utf8&amp;amp;autoReconnect=true&amp;amp;useSSL=false&amp;amp;serverTimezone=Asia/Shanghai"
                    userId="root"
                    password="root">
    </jdbcConnection>

    <javaTypeResolver >
        <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <!--生成Java Model即Entity實體類-->
    <javaModelGenerator targetPackage="com.citi.entity" targetProject="./src/main/java">
        <property name="enableSubPackages" value="true" />
        <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!--SQL XML映射檔案生成器-->
    <sqlMapGenerator targetPackage="mappers"  targetProject="./src/main/resources">
        <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!--生成Mapper接口-->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.citi.mapper"  targetProject="./src/main/java">
        <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!--生成器所用到的表,配置生成的實體類名-->
    <table schema="test" tableName="t_cat" domainObjectName="Cat" >
        <!--<property name="useActualColumnNames" value="true"/>-->
        <!--<generatedKey column="ID" sqlStatement="DB2" identity="true" />-->
        <!--<columnOverride column="DATE_FIELD" property="startDate" />-->
        <!--<ignoreColumn column="FRED" />-->
        <!--<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />-->
    </table>

    <table schema="test" tableName="t_employee" domainObjectName="Employee" >
    </table>
    <table schema="test" tableName="t_teacher" domainObjectName="Teacher" >
    </table>

</context>           

複制

```

運作方式主要有三種,第一種是通過指令行的方式生成代碼

java -jar mybatis-generator-core-x.x.x.jar -configfile \temp\generatorConfig.xml -overwrite           

複制

第二種方式是在test包下新增測試代碼,通過執行Java代碼生成代碼

public class MyBatisGenerator {

    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
                callback, warnings);
        //代碼生成
        myBatisGenerator.generate(null);
        System.out.println("代碼生成器運作結束");
    }

}           

複制

第三種方式是通過通過Maven插件的方式生成代碼,在pom.xml中增加build配置

<build>
    <finalName>mybatis-mbg-pagehelper</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.4.0</version>
            <configuration>
                <!--是否覆寫原有代碼-->
                <overwrite>true</overwrite>
                <verbose>true</verbose>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.16</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>           

複制

打開右側側邊欄的Maven目錄下的Plugins,多出一個mybatis-generator插件

Data Access 之 MyBatis(七)- MBG &amp;amp; PageHelper

輕按兩下該插件即可生成代碼

Data Access 之 MyBatis(七)- MBG &amp;amp; PageHelper

控制台輸出BUILD SUCCESS,說明已經成功生成了Mapper接口、Mapper映射檔案以及Entity實體類代碼

可以看出entity包中除了實體類還有XXXEXample類,這是用來封裝查詢條件的實體類,MyBatis除了生成簡單的CRUD代碼,還生成了複雜查詢的代碼,mapper包中的Mapper接口封裝複雜查詢的方法,mappers目錄下的Mapper XML檔案中也實作了複雜查詢的SQL語句。

當然,MyBatis也支援生成隻有簡單的CRUD代碼,隻需要講generatorConfig.xml檔案中context标簽的屬性更改一下就可以

<context id="test" targetRuntime="MyBatis3Simple" >
<!--中間内容無變化-->
</context>           

複制

在context标簽增加新的标簽,去除自動生成的注釋

<commentGenerator>
    <!-- 是否去除自動生成的注釋 true:是 : false:否 -->
    <property name="suppressAllComments" value="true"/>
</commentGenerator>           

複制

1.2 測試

在test包下建立TeacherMapperTest類

public class TeacherMapperTest {

    SqlSessionFactory sqlSessionFactory = null;
    SqlSession openSession = null;

    @Before
    public void setUp() throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        openSession = sqlSessionFactory.openSession();
    }

    @After
    public void tearDown(){
        openSession.close();
    }
    
    @Test
    public void selectByExample() {
        TeacherMapper teacherMapper = openSession.getMapper(TeacherMapper.class);
        TeacherExample example = new TeacherExample();
        example.setOrderByClause("id DESC");
        TeacherExample.Criteria criteria = example.createCriteria();
        criteria.andClassNameLike("三年%");
        List<Teacher> teachers = teacherMapper.selectByExample(example);
        for (Teacher teacher : teachers) {
            System.out.println(teacher.getId());
        }
    }
}           

複制

Data Access 之 MyBatis(七)- MBG &amp;amp; PageHelper

TeacherExample是用來構造查詢條件的實體類,可以用來設定SQL語句中的order by、distinct、or等關鍵字。 而where後面的查詢條件如:class_name like '%三年%'或者 id between 2,3 或者大于小于等都需要通過TeacherExample調用createCriteria()方法生成一個Criteria類, 然後設定查詢條件

Data Access 之 MyBatis(七)- MBG &amp;amp; PageHelper

執行該測試方法

Data Access 之 MyBatis(七)- MBG &amp;amp; PageHelper

控制它列印出的SQL語句,實作了條件查詢

二、PageHelper

快速進行分頁的插件

1. 引入分頁插件

在 pom.xml 中添加如下依賴:

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.3.0</version>
</dependency>           

複制

2. 配置攔截器插件

1. 在 MyBatis 配置 xml 中配置攔截器插件

<!--
plugins在配置檔案中的位置必須符合要求,否則會報錯,順序如下:
properties?, settings?,
typeAliases?, typeHandlers?,
objectFactory?,objectWrapperFactory?,
plugins?,
environments?, databaseIdProvider?, mappers?
-->
<plugins>
    <!-- com.github.pagehelper為PageHelper類所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- 使用下面的方式配置參數,後面會有所有的參數介紹 -->
        <property name="param1" value="value1"/>
    </plugin>
</plugins>           

複制

TeacherMapper中新增方法insertBatch,批量插入資料用于分頁

int insertBatch(@Param("teacherList") List<Teacher> teacherList);           

複制

在TeacherMapper.xml中增加SQL 映射語句

<insert id="insertBatch">
  INSERT INTO t_teacher(teacher_name, class_name, address, birth_date)
  VALUES
  <foreach collection="teacherList" separator="," item="teacher">
      (#{teacher.teacherName}, #{teacher.className}, #{teacher.address}, #{teacher.birthDate})
  </foreach>
</insert>           

複制

在TeacherMapperTest中增加測試方法

@Test
public void insertBatch(){
    TeacherMapper teacherMapper = openSession.getMapper(TeacherMapper.class);
    List<Teacher> teacherList = new ArrayList<>();
    for (int i = 0; i < 51; i++) {
        Teacher teacher = new Teacher();
        teacher.setTeacherName("Mark " + i);
        teacher.setClassName("三年" + i+ "班");
        teacher.setAddress("New York");
        teacher.setBirthDate(new Date());
        teacherList.add(teacher);
    }
    teacherMapper.insertBatch(teacherList);
    openSession.commit();
}           

複制

執行該測試,往資料庫中插入50條資料

TeacherMapper接口中新增方法,擷取所有的Teacher,對查詢結果使用分頁

List<Teacher> getAllTeachers();           

複制

在TeacherMapper.xml中增加SQL映射

<select id="getAllTeachers" resultType="com.citi.entity.Teacher">
  select * from t_teacher
</select>           

複制

在test包下的TeacherMapperTest中增加測試方法

@Test
public void getAllTeachers(){
    TeacherMapper teacherMapper = openSession.getMapper(TeacherMapper.class);
    // 緊跟着PageHelp的查詢是分頁查詢,其他的就是查詢全部
    PageHelper.startPage(4,5);
    List<Teacher> teacherList = teacherMapper.getAllTeachers();


    // 将查詢的結果使用pageInfo封裝
    PageInfo<Teacher> pageInfo = new PageInfo<>(teacherList);
    System.out.println("目前頁碼為:" + pageInfo.getPageNum());
    System.out.println("總頁碼數:" + pageInfo.getPages());
    System.out.println("總記錄數:" + pageInfo.getTotal());
    System.out.println("目前頁面記錄數:" + pageInfo.getSize());
    System.out.println("上一頁:" + pageInfo.getPrePage());
    System.out.println("下一頁:" + pageInfo.getNextPage());
}           

複制

執行測試

Data Access 之 MyBatis(七)- MBG &amp;amp; PageHelper

控制台成功輸出分頁相關的資訊