MyBatis之逆向工程

情景:当你一个工程中涉及二十个、三十个表时,你都要一个一个的写映射文件和实体类吗?
这时你就可以用逆向工程工具很容易实现这些操作了。

逆向工程

逆向工程:表–>生成实体类
Mapper接口
Mapper映射文件

下载逆向工程

下载地址:https://github.com/mybatis/generator/releases/tag/mybatis-generator-1.3.2

重要代码

操作都一样,自己改改,这个是基于maven工程写的,文件是存放在src/main/java下的

java工程 文件存放在src

①:需要的jar包有:

mybatis-3.2.7.jar
mysql-connector-java-5.1.26.jar
mybatis-generator-core-1.3.5.jar

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.itqf</groupId>
  <artifactId>mybatis_day02_04_generator</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
  		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.2.7</version>
	</dependency>
	<!-- mysql的驱动 -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>5.1.26</version>
		</dependency>
	<!-- generator工具包 -->	
	<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.5</version>
</dependency>  
  </dependencies>
</project>

②:

generator.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="testTables" targetRuntime="MyBatis3">
		<commentGenerator>
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql:///pet" userId="root"
			password="111111">
		</jdbcConnection>
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- targetProject:生成PO类的位置 -->
		<javaModelGenerator targetPackage="com.tf.domain"
			targetProject="./src/main/java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
			<!-- 从数据库返回的值被清理前后的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
		<!-- targetProject:mapper映射文件生成的位置 -->
		<sqlMapGenerator targetPackage="com.tf.mapper"
			targetProject="./src/main/java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false " />
		</sqlMapGenerator>
		<!-- targetPackage:mapper接口生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.tf.mapper" targetProject="./src/main/java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>
		<!-- 指定数据库表 如果不想生成Example文件 就可以设置
			enableXXXByExample="false"  不生成该方法
		 -->
		<table tableName="pets" enableCountByExample="false"
		enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"></table>
		
		<table tableName="types" enableCountByExample="false"
		enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"></table>
		
		
	</context>
</generatorConfiguration>


测试类:

public class TestGenerator {
	public static void main(String[] args) throws Exception{
		    List<String> warnings = new ArrayList<String>();
		   boolean overwrite = true;
		   File configFile = new File("src/main/resources/generator.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);
	}
}

完毕之后,记住fresh一下
如果出现这些,就成功了:
​​​​​​​​​​成功

将逆向工程生成的代码拷贝到指定项目中

注意事项:

Mapper.xml文件已经存在时,如果进行重新生成则mapper.xml文件时,内容不被覆盖而是进行内容追加,导致mybatis解析失败。

解决方法:删除原来已经生成的mapper xml文件再进行生成。

Mybatis自动生成的po及mapper.java文件不是内容而是直接覆盖没有此问题。

Example查询

如果想生成example文件在xml中,改为这样既可

  <table tableName="types"></table>

== Example:where后的条件==

方法的功能说明

int countByExample(XXXExample example) 按条件计数
int deleteByPrimaryKey(Integer id) 按主键删除
int deleteByExample(XXXExample example) 按条件删除
String/Integer insert(XXX record) 插入数据
XXX selectByPrimaryKey(Integer id) 按主键查询
ListselectByExample(XXXExample example) 按条件查询
ListselectByExampleWithBLOGs(XXXExample example)
按条件查询(包括BLOB字段)。只有当数据表中的字段类型有为二进制的才会产生。
int updateByPrimaryKey(XXX record) 按主键更新
int updateByPrimaryKeySelective(XXX record) 按主键更新值不为null的字段
int updateByExample(XXX record, XXXExample example) 按条件更新
int updateByExampleSelective(XXX record, XXXExample example) 按条件更新值不为null的字段

注:带有Selective 的方法,都要判断属性是否为空,如果不为空再操作
比如:

    Pets  p = new Pets();
    p.setName("呼呼");
 	petsMapper.insert(p);  //插入字段 ,其余字段默认值   insert into pets (id, name, birth_date, type_id, owner_id) values (?, ?, ?, ?, ?) 
 	petsMapper.insertSelective(p);   //insert into pets ( name ) values ( ? )

全查:

        select id, name, birth_date, type_id, owner_id from pets
 List<Pets> list =  petsMapper.selectByExample(null);  

模糊查询

  WHERE ( name like ? )
    PetsExample example = new PetsExample();
     Criteria criteria = example.createCriteria();
      List<Pets> list =  petsMapper.selectByExample(example);

范围查询

WHERE ( id between ? and ? ) 
PetsExample example = new PetsExample();
 Criteria criteria = example.createCriteria();
 criteria.andIdBetween(111, 115);
List<Pets> list =  petsMapper.selectByExample(example);

运算查询

WHERE ( id >= ? )

 criteria.andIdGreaterThanOrEqualTo(114);

降序查询

  example.setOrderByClause("id desc");

or条件查询:

name like ? or id>=?

  PetsExample example = new PetsExample();
 	Criteria criteria = example.createCriteria();
 	criteria.andNameLike("%包子%");
   Criteria criteria1 = example.createCriteria();
 	criteria1.andIdGreaterThanOrEqualTo(112);
 	example.or(criteria1);
 	List<Pets> list =  petsMapper.selectByExample(example);

example条件实例解析

mybatis的逆向工程中会生成实例及实例对应的example,example用于添加条件,相当where后面的部分

xxxExample example = new xxxExample();
Criteria criteria = example .createCriteria()

  1. example.setOrderByClause(“字段名 ASC”); 添加升序排列条件,DESC为降序
  2. example.setDistinct(false) 去除重复,boolean型,true为选择不重复的记录。
  3. criteria.andXxxIsNull 添加字段xxx为null的条件
  4. criteria.andXxxIsNotNull 添加字段xxx不为null的条件
  5. criteria.andXxxEqualTo(value) 添加xxx字段等于value条件
  6. criteria.andXxxNotEqualTo(value) 添加xxx字段不等于value条件
  7. criteria.andXxxGreaterThan(value) 添加xxx字段大于value条件
  8. criteria.andXxxGreaterThanOrEqualTo(value) 添加xxx字段大于等于value条件
  9. criteria.andXxxLessThan(value) 添加xxx字段小于value条件
  10. criteria.andXxxLessThanOrEqualTo(value) 添加xxx字段小于等于value条件
  11. criteria.andXxxIn(List<?>) 添加xxx字段值在List<?>条件
  12. criteria.andXxxNotIn(List<?>) 添加xxx字段值不在List<?>条件
  13. criteria.andXxxLike(“%”+value+”%”) 添加xxx字段值为value的模糊查询条件
  14. criteria.andXxxNotLike(“%”+value+”%”) 添加xxx字段值不为value的模糊查询条件
  15. criteria.andXxxBetween(value1,value2) 添加xxx字段值在value1和value2之间条件
  16. criteria.andXxxNotBetween(value1,value2) 添加xxx字段值不在value1和value2之间条件

@Param注解:

xxxMappers.java

int updateByExampleSelective(@Param(“record”) Pets record, @Param(“example”) PetsExample example);
@Param(“record”)注解,可以把参数封装为Map<String,Object>

这句话等价于:

Map<Stirng ,Object> map = new HashMap<String,Object>();
map.put("record",record);
map.put("example",example);

注意:生成的mapper文件,也可以自己封装方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值