mybatis逆向工程 + 通用mapper

pom.xml

<!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--通用 mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>

        <!-- mybatis 逆向生成工具  -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator</artifactId>
            <version>1.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
        </dependency>

application.properties

# mybatis 配置
mybatis.type-aliases-package=com.demo.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

# 通用 Mapper 配置
mapper.mappers=com.demo.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL

generatorConfig.xml

和pom.xml在同級目錄

<?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>
<!--導入屬性配置-->
    <properties resource="datasource.properties"></properties><!--導入鏈接數據庫的參數和驅動-->

    <context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
<!-- 配置生成pojo的序列化的插件,mybatis支持很多插件,這些插件都在 org.mybatis.generator.plugins包下  -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

        <!-- 配置生成pojo的toString()方法的插件,mybatis支持很多插件,這些插件都在 org.mybatis.generator.plugins包下 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
   
        <!--結合通用Mapper插件 指定生成 Mapper 的繼承模板-->
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.demo.utils.MyMapper"/>
        </plugin>
        
		<!--覆蓋生成XML文件 每次執行,把以前的mapper.xml覆蓋而不是合併-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
        
        <!--注意, plugin 需要寫在commentGenerator上面-->
        
        <commentGenerator>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="false" />
        </commentGenerator>

        <!-- 生成 JavaBean 對象重寫 toString方法 -->
<!--        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />-->
        <!-- 生成 JavaBean 對象繼承 Serializable 類 -->
<!--        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />-->
        <!-- 生成 JavaBean 對象重寫 equals 和 hashCode 方法 -->
        <!-- <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" /> -->

        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="${db.url}"
                        userId="${db.username}"
                        password="${db.password}">
        </jdbcConnection>
        
        <!-- 對應生成的pojo所在包 -->
        <javaModelGenerator targetPackage="com.demo.pojo" targetProject="src/main/java">
            <!-- 是否對model添加 構造函數 -->
            <property name="constructorBased" value="true"/>
        </javaModelGenerator>

		<!-- 對應生成的mapper所在目錄 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>

		<!-- 配置mapper對應的java映射 -->
        <javaClientGenerator targetPackage="com.demo.mapper" targetProject="src/main/java"
                             type="XMLMAPPER"/>

		<!--指定要處理的數據庫表 domainObjectName是指定生成的文件名,可不寫 但發現如果有多個數據庫名字一樣,會有問題,所以最好寫下-->
		 <table tableName="device" domainObjectName="Device">
            <!--新增時,能返回id-->
            <generatedKey  column="device_id" sqlStatement="SELECT LAST_INSERT_ID()"/>
        </table>
        <table tableName="print_file" domainObjectName="PrintFile">
            <generatedKey  column="file_id" sqlStatement="SELECT LAST_INSERT_ID()"/>
        </table>
		 
    </context>
</generatorConfiguration>

MyMapper

路徑 com.demo.utils.MyMapper


import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
    //TODO
    //FIXME 特別注意,該接口不能被掃描到,否則會出錯
}

最後的執行文件GeneratorDisplay.java

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class GeneratorDisplay {

	public void generator() throws Exception{

		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		//指定 逆向工程配置文件
		File configFile = new File("src/main/resources/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);

	}

	public static void main(String[] args) throws Exception {
		try {
			GeneratorDisplay generatorSqlmap = new GeneratorDisplay();
			generatorSqlmap.generator();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

datasource.properties

db.url=jdbc:mysql://localhost:3306/gdpt_posmart_office?serverTimezone=UTC&useSSL=false
db.username=root
db.password=root
# 其他參數

常見問題

1.熱部署衝突,提示 tk.mybatis.mapper.MapperException: tk.mybatis.mapper.provider.EmptyProvider中缺少selectOne方法!

https://blog.csdn.net/yinaoxiao7661/article/details/88737604

2.獲取自增長id

方式一:
添加
useGeneratedKeys=“true” keyProperty=“fileId” keyColumn=“file_id”

<insert id="myInsert" parameterType="com.gdpt.crawlerprint.pojo.PrintFile"
          useGeneratedKeys="true" keyProperty="fileId" keyColumn="file_id">
    insert into cp_print_file (user_id, filename,
    file_type, upload_date)
    values (#{userId,jdbcType=INTEGER}, #{filename,jdbcType=VARCHAR},
    #{fileType,jdbcType=BIT}, #{uploadDate,jdbcType=TIMESTAMP})
  </insert>

獲取自增長id

		printFileMapper.myInsert(printFile);
		int id = 0;
        if (printFile.getFileId() != null){
            id = printFile.getFileId();
        }

方式二:
generatorConfig.xml配置中

		<table tableName="print_file" domainObjectName="PrintFile">
            <!--新增時,能返回id-->
            <generatedKey  column="file_id" sqlStatement="SELECT LAST_INSERT_ID()"/>
        </table>

獲取自增長id

		printFileMapper.insert(printFile);
		int id = 0;
        if (printFile.getFileId() != null){
            id = printFile.getFileId();
        }

3.常用接口解釋

    //(1)mapper基礎接口
    //select接口
      List<VirtualIpBean> vipList = vipMapper.select(vipBean);//根據實體中的屬性值進行查詢,查詢條件使用等號
    VirtualIpBean vip = vipMapper.selectOne(vipBean);//根據實體中的屬性進行查詢,只能有一個返回值,有多個結果是拋出異常,查詢條件使用等號
    List<VirtualIpBean> vipList2 = vipMapper.selectAll();//查詢全部結果,select(null)方法能達到同樣的效果
    VirtualIpBean vip2 = vipMapper.selectByPrimaryKey(1);//根據主鍵字段進行查詢,方法參數必須包含完整的主鍵屬性,查詢條件使用等號
    int count = vipMapper.selectCount(vipBean);//根據實體中的屬性查詢總數,查詢條件使用等號
    //insert接口
    int a = vipMapper.insert(vipBean);//保存一個實體,null的屬性也會保存,不會使用數據庫默認值
    int a1 = vipMapper.insertSelective(vipBean);//保存實體,null的屬性不會保存,會使用數據庫默認值
    //update接口
    int b = vipMapper.updateByPrimaryKeySelective(vipBean);//根據主鍵更新屬性不爲null的值
    int c = vipMapper.updateByPrimaryKey(vipBean);//根據主鍵更新實體全部字段,null值會被更新
    //delete接口
    int d = vipMapper.delete(vipBean);//根據實體屬性作爲條件進行刪除,查詢條件使用等號
    int e = vipMapper.deleteByPrimaryKey(1);//根據主鍵字段進行刪除,方法參數必須包含完整的主鍵屬性
    //(2)Example方法
    Example example = new Example(VirtualIpBean.class);
    example.createCriteria().andEqualTo("id", 1);
    example.createCriteria().andLike("val", "1");
    //自定義查詢
    List<VirtualIpBean> vipList3 = vipMapper.selectByExample(example);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章