觉得文章太长可以直接看文章末尾的总结。
逆向工程简介
什么是逆向工程:
mybatis需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper.java、mapper.xml、pojo…),可以让程序员将更多的精力放在繁杂的业务逻辑上。
企业实际开发中,常用的逆向工程方式:由数据库的表生成java代码。
之所以强调单表两个字,是因为Mybatis逆向工程生成的Mapper所进行的操作都是针对单表的,也许你可能会觉得那这就有点鸡肋了,但是在大型项目中,很少有复杂的多表关联查询,所以作用还是很大的。
逆向工程的使用
运行逆向工程(摘自官网):
翻译过来就是:
- 从带有XML配置的命令提示符
- 作为具有XML配置的Ant任务
- 作为一个Maven插件
- 从另一个java程序,基于XML配置
- 从另一个java程序,基于java的配置
- 通过Eclipse插件
一般来说,我们会选择使用一个Java程序,基于XML配置来生成代码,下面来介绍具体操作。
代码的生成
数据表:
Java工程结构:
GeneratorSqlmap.java
package xin.luxinda.NXProject; import java.io.File; import java.util.*; 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; public class GeneratorSqlmap { public void generator() throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; // 指定配置文件 File configFile = new File("./config/NXProject/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); } // 执行main方法以生成代码 public static void main(String[] args) { try { GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap(); generatorSqlmap.generator(); } catch (Exception e) { e.printStackTrace(); } } }
generatorConfig.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> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自动生成的注释 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- Mysql数据库连接的信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/e3mall" userId="root" password="111"> </jdbcConnection> <!-- Oracle数据库 <jdbcConnection driverClass="oracle.jdbc.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg" password="yycg"> </jdbcConnection> --> <!-- 默认为false,把JDBC DECIMAL 和NUMERIC类型解析为Integer,为true时 把JDBC DECIMAL 和NUMERIC类型解析为java.math.BigDecimal --> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:生成POJO类的位置 --> <javaModelGenerator targetPackage="cn.e3mall.pojo" targetProject=".\src"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="cn.e3mall.mapper" targetProject=".\src"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetProject:mapper接口生成的的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.e3mall.mapper" targetProject=".\src"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定数据表 --> <table schema="" tableName="tb_content"></table> <table schema="" tableName="tb_content_category"></table> <table schema="" tableName="tb_item"></table> <table schema="" tableName="tb_item_cat"></table> <table schema="" tableName="tb_item_desc"></table> <table schema="" tableName="tb_item_param"></table> <table schema="" tableName="tb_item_param_item"></table> <table schema="" tableName="tb_order"></table> <table schema="" tableName="tb_order_item"></table> <table schema="" tableName="tb_order_shipping"></table> <table schema="" tableName="tb_user"></table> <!-- 有些表的字段需要指定java类型 <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" > <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> --> </context> </generatorConfiguration>
配置文件需要修改的内容:
- 数据库驱动、地址、用户名、密码
- POJO类、mapper接口、mapper映射文件生成的位置
- 指定数据表
配置完成之后运行GeneratorSqlmap.java中的main方法就会生成对应数据表的代码,生成后记得右键项目名刷新。如果需要再次生成,一定要记得先把原来生成的删除。
生成的代码:
如果有N张表,就会生成2N个POJO,N个mapper.java以及N个mapper.xml,也许你会问,为什么会生成2N个POJO呢?那是因为他除了常规的POJO之外还生成了用于设置条件的xxxExample,比如图中的TbItem.java和TbItemExample.java,Example的具体使用会在后面的代码使用中详细说。
代码的使用
---------------------------------------------------------------------------------
查询
首先说一下查询的不足之处:不能指定查询的列,只能够查询所有列。
我们可以看到,有三个查询方法(一般来说只有两个查询方法,第二个查询方法只会在特定条件下出现)
方法1:selectByExample(TbItemDescExample example)
返回值:List<TbItemDesc>
作用:通过特定限制条件查询信息,example用于生成一个Criteria对象来设置查询条件
例:
TbItemDescExample example = new TbItemDescExample(); cn.e3mall.pojo.TbItemDescExample.Criteria criteria = example.createCriteria(); long minId = 0; long maxId = 50; criteria.andItemIdBetween(minId, maxId); // 设置条件:ItemId在 0 和 50 之间 List<Long> ids = new ArrayList<>(); ids.add((long)20); ids.add((long)40); ids.add((long)60); criteria.andItemIdIn(ids); // 设置条件:ItemId等于 20 或 40 或 60 criteria.andCreatedIsNotNull(); // 设置条件:Created列属性不为空 long id = 40; criteria.andItemIdEqualTo(id); // 设置条件:ItemId等于40 // 执行查询 List<TbItemDesc> selectByExample = itemDescMapper.selectByExample(example);
具体可设置的条件很多很多,根据表的结构的不同会有不同的可限制条件,比如:
在这里就不一个一个解释了,根据字面意思,很好理解的。
方法2:selectByPrimaryKey(Long itemId)
返回值:TbItemDesc
作用:通过主键查询
方法3:selectByExampleWithBLOBs(TbItemDescExample example)
返回值:List<TbItemDesc>
作用:根据特定限制条件查询,返回值包含类型为text的列(默认查询并不会返回该列的信息)。example用于生成一个Criteria对象来设置查询条件,具体使用方法和方法1是一样的,唯一的把不同就是返回值是所有列。
---------------------------------------------------------------------------------
插入
插入很简单,只有两个方法,方法传入的参数都是POJO,返回值都是int类型的受影响的行数。不同之处在于insert会插入所有的信息,如果传入的对象某一属性为空,则插入空,如果数据库中设置了默认值,默认值就失效了。而insertSelective不同,他只会插入含有数据的属性,对于为空的属性,不予以处理,这样的话如果数据库中设置有默认值,就不会被空值覆盖了。
---------------------------------------------------------------------------------
删除
---------------------------------------------------------------------------------
更新
更新在这里有6个方法,可以分为2组:
第一组:根据特定限制条件进行更新
参数1:TbItemDesc record -> 要更新的对象
参数2:TbItemDescExample example -> 生成一个Criteria对象来设置查询条件
方法1:updateByExample(TbItemDesc record, TbItemDescExample example)
作用:根据特定的限制条件进行更新除了text类型(数据库)的所有列。
方法2:updateByExampleSelective(TbItemDesc record, TbItemDescExample example)
作用:根据特定的限制条件更新所有设置了值的列。
方法3:updateByExampleWithBLOBs(TbItemDesc record, TbItemDescExample example)
作用:根据特定的限制条件进行更新所有列。
第二组:根据ID进行更新
参数:TbItemDesc record -> 要更新的对象
方法1:updateByPrimaryKey(TbItemDesc record)
作用:通过ID更新除了text类型(数据库)的所有列
方法2:updateByPrimaryKeySelective(TbItemDesc record)
作用:通过ID更新所有设置了值的列。
方法3:updateByPrimaryKeyWithBLOBs(TbItemDesc record)
作用:通过ID进行更新所有列。
---------------------------------------------------------------------------------
计数
---------------------------------------------------------------------------------
总结:
- Example和Primarykey用来指定要 删除 / 更新 / 查询 的行。
- 不加后缀、Selective后缀、WithBLOBs后缀用来限制要 删除 / 更新 / 查询 的列。
持续更新,如有错误之处还望指正......