Mybatis逆向工程

觉得文章太长可以直接看文章末尾的总结吐舌头

逆向工程简介

什么是逆向工程:

        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

1. package xin.luxinda.NXProject;
2.  
3. import java.io.File;
4. import java.util.*;
5.  
6. import org.mybatis.generator.api.MyBatisGenerator;
7. import org.mybatis.generator.config.Configuration;
8. import org.mybatis.generator.config.xml.ConfigurationParser;
9. import org.mybatis.generator.internal.DefaultShellCallback;
10.  
11. public class GeneratorSqlmap {
12.  
13.public void generator() throws Exception {
14. ​		List<String> warnings = new ArrayList<String>();
15.boolean overwrite = true;
16.// 指定配置文件
17. ​		File configFile = new File("./config/NXProject/generatorConfig.xml");
18. ​		ConfigurationParser cp = new ConfigurationParser(warnings);
19. ​		Configuration config = cp.parseConfiguration(configFile);
20. ​		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
21. ​		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
22. ​		myBatisGenerator.generate(null);
23.}
24.  
25.// 执行main方法以生成代码
26.public static void main(String[] args) {
27.try {
28. ​			GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
29. ​			generatorSqlmap.generator();
30.} catch (Exception e) {
31. ​			e.printStackTrace();
32.}
33.}
34. }

generatorConfig.xml

1. <?xml version="1.0" encoding="UTF-8"?>
2. <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
3.  
4. <generatorConfiguration>
5.   <context id="DB2Tables" targetRuntime="MyBatis3">
6.<commentGenerator>
7.<!-- 是否去除自动生成的注释 -->
8.<property name="suppressAllComments" value="true"/>
9.</commentGenerator>
10.<!-- Mysql数据库连接的信息:驱动类、连接地址、用户名、密码 -->
11.<jdbcConnection driverClass="com.mysql.jdbc.Driver"
12. ​        connectionURL="jdbc:mysql://localhost:3306/e3mall"
13. ​        userId="root"
14. ​        password="111">
15.</jdbcConnection>
16.<!-- Oracle数据库
17.<jdbcConnection driverClass="oracle.jdbc.OracleDriver"
18. ​	        connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
19. ​	        userId="yycg"
20. ​	        password="yycg">
21.</jdbcConnection> 
22.-->
23.24.<!-- 默认为false,把JDBC DECIMAL 和NUMERIC类型解析为Integer,为true25. ​	把JDBC DECIMAL 和NUMERIC类型解析为java.math.BigDecimal -->
26.<javaTypeResolver >
27.<property name="forceBigDecimals" value="false" />
28.</javaTypeResolver>
29.30.<!-- targetProject:生成POJO类的位置 -->
31.<javaModelGenerator targetPackage="cn.e3mall.pojo" targetProject=".\src">
32.<!-- enableSubPackages:是否让schema作为包的后缀 -->
33.<property name="enableSubPackages" value="false" />
34.<!-- 从数据库返回的值被清理前后的空格 -->
35.<property name="trimStrings" value="true" />
36.</javaModelGenerator>
37.38.<!-- targetProject:mapper映射文件生成的位置 -->
39.<sqlMapGenerator targetPackage="cn.e3mall.mapper"  targetProject=".\src">
40.<!-- enableSubPackages:是否让schema作为包的后缀 -->
41.<property name="enableSubPackages" value="false" />
42.</sqlMapGenerator>
43.44.<!-- targetProject:mapper接口生成的的位置 -->
45.<javaClientGenerator type="XMLMAPPER" targetPackage="cn.e3mall.mapper"  targetProject=".\src">
46.<!-- enableSubPackages:是否让schema作为包的后缀 -->
47.<property name="enableSubPackages" value="false" />
48.</javaClientGenerator>
49.50.<!-- 指定数据表 -->
51.<table schema="" tableName="tb_content"></table>
52.<table schema="" tableName="tb_content_category"></table>
53.<table schema="" tableName="tb_item"></table>
54.<table schema="" tableName="tb_item_cat"></table>
55.<table schema="" tableName="tb_item_desc"></table>
56.<table schema="" tableName="tb_item_param"></table>
57.<table schema="" tableName="tb_item_param_item"></table>
58.<table schema="" tableName="tb_order"></table>
59.<table schema="" tableName="tb_order_item"></table>
60.<table schema="" tableName="tb_order_shipping"></table>
61.<table schema="" tableName="tb_user"></table>
62.63.<!-- 有些表的字段需要指定java类型 
64.<table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
65.<property name="useActualColumnNames" value="true"/>
66.<generatedKey column="ID" sqlStatement="DB2" identity="true" />
67.<columnOverride column="DATE_FIELD" property="startDate" />
68.<ignoreColumn column="FRED" />
69.<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
70.</table> -->
71.  
72.   </context>
73. </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对象来设置查询条件

例:

1. TbItemDescExample example = new TbItemDescExample();
2. cn.e3mall.pojo.TbItemDescExample.Criteria criteria = example.createCriteria();
3. long minId = 0;
4. long maxId = 50;
5. criteria.andItemIdBetween(minId, maxId); // 设置条件:ItemId在 0 和 50 之间
6.7. List<Long> ids = new ArrayList<>();
8. ids.add((long)20);
9. ids.add((long)40);
10. ids.add((long)60);
11. criteria.andItemIdIn(ids);	// 设置条件:ItemId等于 20 或 40 或 60
12.13. criteria.andCreatedIsNotNull(); // 设置条件:Created列属性不为空
14.15. long id = 40;
16. criteria.andItemIdEqualTo(id); // 设置条件:ItemId等于40
17.18. // 执行查询
19. 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不同,他只会插入含有数据的属性,对于为空的属性,不予以处理,这样的话如果数据库中设置有默认值,就不会被空值覆盖了。

---------------------------------------------------------------------------------

删除


        方法1:根据特定限制条件删除,具体使用的方法和查询的时候是一样的。
        方法2:根据主键删除。

---------------------------------------------------------------------------------

更新

更新在这里有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在前面已经说过了,在这里就不叙述了。

---------------------------------------------------------------------------------

总结:

  • ExamplePrimarykey用来指定要 删除 / 更新 / 查询 的行。
  • 不加后缀、Selective后缀、WithBLOBs后缀用来限制要 删除 / 更新 / 查询 的列。
参考图(不严谨,仅供理解参考):


持续更新,如有错误之处还望指正......


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值