Mybaties逆向工程快速使用

1 什麼是逆向工程?

mybatis的一個主要的特點就是需要程序員自己編寫sql,那麼如果表太多的話,難免會很麻煩,所以mybatis官方提供了一個逆向工程,可以針對單表自動生成mybatis執行所需要的代碼(包括mapper.xml、mapper.java、pojo)。一般在開發中,常用的逆向工程方式是通過數據庫的表生成代碼。

2 HOW?

2.1 創建maven工程(略)

2.2 pom.xml : 添加插件和依賴

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.5</version>
            <configuration>
                <verbose>true</verbose>
                <overwrite>true</overwrite>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.34</version>
    </dependency>
</dependencies>

2.3 配置文件

在maven項目下的src/main/resources 目錄下建立名爲 generatorConfig.xml的配置文件,作爲mybatis-generator-maven-plugin 插件的執行目標,模板如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--mysql 連接數據庫jar 這裏選擇自己本地位置-->
    <classPathEntry location="E:/Maven_Repository/mysql/mysql-connector-java/5.1.34/mysql-connector-java-5.1.34.jar" />

    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--數據庫連接的信息:驅動類、連接地址、用戶名、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis_db"
                        userId="root"
                        password="123">
        </jdbcConnection>

        <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer,爲 true時把JDBC DECIMAL 和
           NUMERIC 類型解析爲java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO類的位置 -->
        <javaModelGenerator targetPackage="cn.itcast.domain"
                            targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作爲包的後綴 -->
            <property name="enableSubPackages" value="false" />
            <!-- 從數據庫返回的值被清理前後的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置
           如果maven工程只是單獨的一個工程,targetProject="src/main/java"
           若果maven工程是分模塊的工程,targetProject="所屬模塊的名稱",例如:
           targetProject="ecps-manager-mapper",下同-->
        <sqlMapGenerator targetPackage="cn.itcast.mapper"
                         targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作爲包的後綴 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="cn.itcast.mapper"
                             targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作爲包的後綴 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- 指定數據庫表 -->
        <table schema="" tableName="tb_user" domainObjectName="User"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="true"
               selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

2.4 運行插件

使用maven運行mybatis-generator-maven-plugin插件:

工程名->Plugins->mybatis-generator->mybatis-generator:generate->Run Maven Build

自動生成的結構目錄

3 MyBatis的Mapper接口以及Example的實例函數及詳解

3.1 mapper接口的方法

方法 功能說明
int countByExample(UserExample example) thorws SQLException 按條件計數
int deleteByPrimaryKey(Integer id) thorws SQLException 按主鍵刪除
int deleteByExample(UserExample example) thorws SQLException 按條件查詢
String/Integer insert(User record) thorws SQLException 插入數據(返回值爲ID)
User selectByPrimaryKey(Integer id) thorws SQLException 按主鍵查詢
ListselectByExample(UserExample example) thorws SQLException 按條件查詢
ListselectByExampleWithBLOGs(UserExample example) thorws SQLException 按條件查詢(包括BLOB字段)。只有當數據表中的字段類型有爲二進制的纔會產生。
int updateByPrimaryKey(User record) thorws SQLException 按主鍵更新
int updateByPrimaryKeySelective(User record) thorws SQLException 按主鍵更新值不爲null的字段
int updateByExample(User record, UserExample example) thorws SQLException 按條件更新
int updateByExampleSelective(User record, UserExample example) thorws SQLException 按條件更新值不爲null的字段

3.2 Exaple實例解析

mybatis的逆向工程中會生成實例及實例對應的example,example用於添加條件,相當where後面的部分 xxxExample example = new xxxExample();

Criteria criteria = new Example().createCriteria();

方法 說明
example.setOrderByClause(“字段名 ASC”); 添加升序排列條件,DESC爲降序
example.setDistinct(false) 去除重複,boolean型,true爲選擇不重複的記錄。
criteria.andXxxIsNull 添加字段xxx爲null的條件
criteria.andXxxIsNotNull 添加字段xxx不爲null的條件
criteria.andXxxEqualTo(value) 添加xxx字段等於value條件
criteria.andXxxNotEqualTo(value) 添加xxx字段不等於value條件
criteria.andXxxGreaterThan(value) 添加xxx字段大於value條件
criteria.andXxxGreaterThanOrEqualTo(value) 添加xxx字段大於等於value條件
criteria.andXxxLessThan(value) 添加xxx字段小於value條件
criteria.andXxxLessThanOrEqualTo(value) 添加xxx字段小於等於value條件
criteria.andXxxIn(List<?>) 添加xxx字段值在List<?>條件
criteria.andXxxNotIn(List<?>) 添加xxx字段值不在List<?>條件
criteria.andXxxLike(“%”+value+”%”) 添加xxx字段值爲value的模糊查詢條件
criteria.andXxxNotLike(“%”+value+”%”) 添加xxx字段值不爲value的模糊查詢條件
criteria.andXxxBetween(value1,value2) 添加xxx字段值在value1和value2之間條件
criteria.andXxxNotBetween(value1,value2) 添加xxx字段值不在value1和value2之間條件

3.3 應用舉例

3.3.1 查詢

3.3.3.1 根據主鍵查詢用戶信息

select * from tb_user where id=?

package cn.itcast.mapper;

import cn.itcast.domain.User;
import cn.itcast.domain.UserExample;
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.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UserMapperTest {

    private UserMapper userMapper;

    @Before
    public void setUp() throws Exception {
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void selectByPrimaryKey() throws Exception {
        User user = userMapper.selectByPrimaryKey(1L);
        System.out.println(user);
    }

}

3.3.3.2 查詢所有的用戶

select * from tb_user

@Test
public void selectByExample() {
    UserExample example = new UserExample();
    List<User> userList = userMapper.selectByExample(example);
    for (User user : userList) {
        System.out.println(user);
    }
}

3.3.3.3 根據編號查詢多個用戶

select * from tb_user where id in (?, ?, ?)

@Test
public void selectByExample2() {
    UserExample example = new UserExample();

    UserExample.Criteria criteria = example.createCriteria();
    List<Long> idList = new ArrayList<Long>();
    Collections.addAll(idList, 1L, 2L, 3L);
    criteria.andIdIn(idList);
    

    List<User> userList = userMapper.selectByExample(example);
    for (User user : userList) {
        System.out.println(user);
    }
}
@Test
public void selectByExample02() throws Exception {
    // 需求: 查詢所有姓李的用戶信息 和 年齡是28
    UserExample userExample = new UserExample();
    UserExample.Criteria criteria = userExample.createCriteria();
    criteria.andNameLike("%李%");
    criteria.andAgeEqualTo(28);

    List<User> userList = userMapper.selectByExample(userExample);
    System.out.println("===========================================================");
    for (User user : userList) {
        System.out.println(user);
    }
    System.out.println("===========================================================");
}

3.3.2 插入

3.3.2.1 所有字段

@Test
public void insert() throws Exception {
    User user = new User();
    user.setUserName("yangmi");

    userMapper.insert(user);
}

[外鏈圖片轉存失敗(img-MJwOt68d-1565853060337)(assets/1533748920847.png)]

3.3.2.2 不爲null的字段

@Test
public void insertSelective() throws Exception {
    User user = new User();
    user.setUserName("liukaiwei");
    user.setPassword("123");
    user.setName("劉愷威");

    userMapper.insertSelective(user);
}

[外鏈圖片轉存失敗(img-hCKuqQnj-1565853060337)(assets/1533749000782.png)]

3.3.3 修改

3.3.3.1 修改所有字段

@Test
public void updateByPrimaryKey() throws Exception {
    User user = userMapper.selectByPrimaryKey(1L);
    user.setAge(1000);

    userMapper.updateByPrimaryKey(user);
}

[外鏈圖片轉存失敗(img-aaZMB9Tm-1565853060337)(assets/1533749164498.png)]

3.3.3.2 修改部分字段

@Test
public void updateByPrimaryKeySelective() throws Exception {
    User user = new User();
    user.setId(18L);
    user.setUserName("huangxiaoming");
    user.setName("黃曉明");

    userMapper.updateByPrimaryKeySelective(user);
}

[外鏈圖片轉存失敗(img-l56cM3wy-1565853060338)(assets/1533749327303.png)]

3.3.4 刪除

@Test
public void deleteByPrimaryKey() throws Exception {
    userMapper.deleteByPrimaryKey(18L);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章