11. 逆向工程
MyBatis逆向工程就是根据数据库表反向生成java代码和映射文件。
11.1 使用逆向工程
1. Emp表
CREATE TABLE `emp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`job` varchar(255) DEFAULT NULL,
`salary` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
2. 导入逆向工程
3. 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="testTables" targetRuntime="MyBatis3">
<!-- 配置生成toString方法的插件 -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test" userId="root"
password="123456">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL
和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetPackage:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.yong.po"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetPackage:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.yong.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.yong.mapper" targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table schema="" tableName="emp"></table>
</context>
</generatorConfiguration>
4. 运行GeneratorSqlmap.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
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("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 {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. 执行结果
6. 说明
1. 逆向工程生成的就是mapper代理开发
2. 逆向工程生成的都是单表操作
3. 使用逆向告工程的好处,提升开发效率
4. 逆向工程生成的文件,直接使用,不推荐大家修改
5. 执行逆向工程,需要将上一次执行的文件删除,再重新执行
11.2 测试
将生成的java文件和xml映射文件复制到MyBatisDemo项目中。
EmpMapper.java
package com.yong.mapper;
import com.yong.po.Emp;
import com.yong.po.EmpExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface EmpMapper {
int countByExample(EmpExample example);
int deleteByExample(EmpExample example);
int deleteByPrimaryKey(Integer id);
int insert(Emp record);
int insertSelective(Emp record);
List<Emp> selectByExample(EmpExample example);
Emp selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Emp record, @Param("example") EmpExample example);
int updateByExample(@Param("record") Emp record, @Param("example") EmpExample example);
int updateByPrimaryKeySelective(Emp record);
int updateByPrimaryKey(Emp record);
}
11.2.1 方法测试
增加:
方式一:
insert
需要插入表中所有字段(包括主键)
@Test
public void testInsert() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = new Emp();
emp.setId(1);
emp.setName("Yong");
emp.setAge(25);
emp.setSex("男");
emp.setJob("IT");
emp.setSalary(10000D);
//需要插入表中所有字段(包括主键)
int insert = empMapper.insert(emp);
System.out.println(insert);
sqlSession.close();
}
结果:
方式二:
insertSelective
只插入值不为null的字段
@Test
public void testInsertSelective() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = new Emp();
emp.setName("Yong");
emp.setAge(25);
emp.setSex("男");
emp.setSalary(10000D);
//只插入值不为null的字段
int insert = empMapper.insertSelective(emp);
System.out.println(insert);
sqlSession.close();
}
结果:
查询:
方式一:
countByExample
条件查询数目
@Test
public void testCountByExample() {
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
EmpExample example = new EmpExample();
Criteria criteria = example.createCriteria();
criteria.andNameLike("%"+"Y"+"%");
criteria.andJobEqualTo("IT");
int countByExample = empMapper.countByExample(example);
System.out.println(countByExample);
sqlSession.close();
}
结果:
方式二:
selectByPrimaryKey
根据主键查询
@Test
public void testSelectByPrimaryKey() {
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = empMapper.selectByPrimaryKey(1);
System.out.println(emp);
sqlSession.close();
}
结果:
方式三:
selectByExample
根据条件查询
@Test
public void testSelectByExample() {
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
EmpExample example = new EmpExample();
Criteria criteria = example.createCriteria();
criteria.andNameEqualTo("Yong");
List<Emp> emps = empMapper.selectByExample(example);
System.out.println(emps);
sqlSession.close();
}
结果:
修改:
方式一:
updateByPrimaryKey
根据主键修改所有属性
@Test
public void testUpdateByPrimaryKey() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = new Emp();
emp.setId(1);
emp.setName("Jing");
emp.setAge(18);
emp.setSex("女");
emp.setJob("学生");
emp.setSalary(1500D);
int updateByPrimaryKey = empMapper.updateByPrimaryKey(emp);
System.out.println(updateByPrimaryKey);
sqlSession.close();
}
结果:
方式二:
updateByPrimaryKeySelective
根据主键修改不为null的属性
@Test
public void testUpdateByPrimaryKeySelective() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = new Emp();
emp.setId(1);
emp.setName("Yong");
emp.setSex("男");
emp.setJob("程序员");
int updateByPrimaryKeySelective = empMapper.updateByPrimaryKeySelective(emp);
System.out.println(updateByPrimaryKeySelective);
sqlSession.close();
}
结果:
方式三:
updateByExample
根据条件修改所有属性
@Test
public void testUpdateByExample() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = new Emp();
emp.setId(3);
emp.setName("Yong");
emp.setAge(25);
emp.setSex("男");
emp.setJob("JAVA程序员");
emp.setSalary(15000D);
EmpExample example = new EmpExample();
Criteria criteria = example.createCriteria();
criteria.andNameLike("%"+"Y"+"%");
criteria.andJobEqualTo("程序员");
int updateByExampleSelective = empMapper.updateByExampleSelective(emp, example);
System.out.println(updateByExampleSelective);
sqlSession.close();
}
结果:
方式四:
updateByExampleSelective
根据条件修改不为null的属性
@Test
public void testUpdateByExampleSelective() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = new Emp();
emp.setId(1);
emp.setJob("IT");
emp.setSalary(10000D);
EmpExample example = new EmpExample();
Criteria criteria = example.createCriteria();
criteria.andNameLike("%"+"Y"+"%");
criteria.andJobEqualTo("JAVA程序员");
int updateByExampleSelective = empMapper.updateByExampleSelective(emp, example);
System.out.println(updateByExampleSelective);
sqlSession.close();
}
结果:
删除:
方式一:
deleteByPrimaryKey
根据主键删除
@Test
public void testDeleteByPrimaryKey() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
int deleteByPrimaryKey = empMapper.deleteByPrimaryKey(2);
System.out.println(deleteByPrimaryKey);
sqlSession.close();
}
结果:
方式二:
deleteByExample
根据条件删除
@Test
public void testDeleteByExample() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
EmpExample example = new EmpExample();
Criteria criteria = example.createCriteria();
criteria.andSalaryBetween(5000D, 150000D);
int deleteByExample = empMapper.deleteByExample(example );
System.out.println(deleteByExample);
sqlSession.close();
}
结果:
方式二:
deleteByExample
根据条件删除
@Test
public void testDeleteByExample() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
EmpExample example = new EmpExample();
Criteria criteria = example.createCriteria();
criteria.andSalaryBetween(5000D, 150000D);
int deleteByExample = empMapper.deleteByExample(example );
System.out.println(deleteByExample);
sqlSession.close();
}
结果: