1. 什么是逆向工程
简单的理解,Mybatis逆向工程,就是通过相应插件,自动生成Mybatis数据库连接的一些文件。
Mybatis需要编写sql语句,Mybatis官方提供逆向工程,可以针对单表自动生成Mybatis执行所需要的代码(mapper.java、mapper.xml、pojo…),提高工作效率。
2. 逆向工程的搭建
2.1. 准备数据库
搭建数据库,数据库名、表名和字段名自拟。参考如下:
1111.png2.2. 搭建Maven工程
这里采用Maven工程,原因是比较方便,不用下载相应的jar包,只需通过在pom.xml文件中引用的形式添加即可。
第一步:创建Maven工程
第二步:在pom.xml文件中,添加Mybatis逆向工程生成器的jar包和数据库连接工具的jar包。
<!-- 逆向工程生成器 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<!-- MySql 连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
第三步:在工程目录的resources资源目录下创建配置文件,名字自拟。并修改文件为如下内容,参照注释自行修改相关配置。
<?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.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" userId="root"
password="5201314">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.demon.pojo"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.demon.dao"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.demon.dao"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<table schema="" tableName="teacher"/>
<table schema="" tableName="student"/>
<!-- 有些表的字段需要指定java类型
<table schema="" tableName="">
<columnOverride column="" javaType="" />
</table> -->
</context>
</generatorConfiguration>
第四步:创建执行脚本Main.java,注意File访问路径为配置文件全路径。
public static void main(String[] args){
try {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("D:\\JavaProjects\\reverseproject\\src\\main\\resources\\SqlMapConfig.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);
}
catch (Exception e){
e.printStackTrace();
}
}
第五步:执行脚本Main.java,会自动生成映射文件、接口文件和pojo等,参考工程目录如下:
2222.png3. 映射文件接口的使用
以上生成的映射文件,下面将根据StudentMapper接口文件分为查找、删除、插入和更新四个板块分别介绍接口的运用,StudentMapper.java接口文件如下:
public interface StudentMapper {
long countByExample(StudentExample example);
int deleteByExample(StudentExample example);
int deleteByPrimaryKey(Integer id);
int insert(Student record);
int insertSelective(Student record);
List<Student> selectByExample(StudentExample example);
Student selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Student record, @Param("example") StudentExample example);
int updateByExample(@Param("record") Student record, @Param("example") StudentExample example);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
}
3.1. 接口使用准备工作
3.1.1 引入jar包
在使用接口文件的时候,必须引用Mybatis的jar包。为了方便测试,这里还引入了测试相关的jar包;采用Spring整合,引入Spring相关jar包;查看日志文件引入log4j的jar包;同时还需要配置资源自动拷贝;最终配置如下:
<dependencies>
<!-- 逆向工程生成器 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<!-- 数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!-- 日志处理 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
<build>
<!-- 如果不配置mybatis的配置文件会漏掉 -->
<!-- 注意:配置了此方式,原来的默认的资源拷贝行为将无效 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
3.1.2 配置相关文件
配置Spring配置文件ApplicationContext.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!-- 数据源 -->
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/test?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="5201314"/>
</bean>
<!-- sqlsessionfactory -->
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.demon.dao" />
</bean>
</beans>
配置日志打印文件log4j.properties如下:
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
3.1.3 添加测试脚本
首先引入@Before注释,初始化ApplicationContext,方便后面使用。
private ApplicationContext context;
@Before
public void initContext() {
this.context = new ClassPathXmlApplicationContext("classpath:ApplicationContext.xml");
}
最终工程目录截图如下:
2222.png3.2. 查找接口使用
countByExample顾名思义是,通过StudentExample的筛选条件完成搜索结果个数的统计,参考代码如下:
@Test
public void testCountByExample() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
StudentExample studentExample = new StudentExample();
//设置查询条件,不设置则全部查询
Criteria criteria = studentExample.createCriteria();
criteria.andIdGreaterThanOrEqualTo(2);
long number = studentMapper.countByExample(studentExample);
System.out.println(number);
}
selectByExample通过StudentExample的筛选条件完成搜索结果,并返回Student的List对象。
@Test
public void testSelectByExample() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
StudentExample studentExample = new StudentExample();
//设置查询条件,必须同时满足
// Criteria criteria = studentExample.createCriteria();
// criteria.andSexEqualTo(2);
// criteria.andNameLike("Demon");
//设置查询条件,满足一个条件即可
Criteria criteria = studentExample.createCriteria();
criteria.andSexEqualTo(2);
Criteria criteria1 = studentExample.or();
criteria1.andNameLike("Demon");
List<Student> studentList = studentMapper.selectByExample(studentExample);
for (Student student:studentList) {
System.out.println(student.getId());
}
}
selectByPrimaryKey,根据主键返回Student对象。
@Test
public void testSelectByPrimaryKey() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
Student student = studentMapper.selectByPrimaryKey(2);
System.out.println(student.getName());
}
3.3. 插入接口使用
insert,直接插入Student对象,插入成功返回1。
@Test
public void testInsert() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
Student student = new Student();
student.setName("Demon");
student.setSex(1);
int result = studentMapper.insert(student);
System.out.println(result);
}
insertSelective,直接插入Student对象,插入成功返回1。 而与insert不同的是,他只会插入含有数据的属性,对于为空的属性,不予以处理,这样的话如果数据库中设置有默认值,就不会被空值覆盖。
@Test
public void testInsertSelective() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
Student student = new Student();
student.setName("Demon");
int result = studentMapper.insertSelective(student);
System.out.println(result);
}
3.4. 更新接口使用
updateByExample,这个接口由两个参数一个Student,一个StudentExample。第一个是要更新的内容,注意如果数据库字段中有不能为空的,一定要在这里设置,不然会报错的,比如id;第二个参数是需要更新的筛选项。
@Test
public void testUpdateByExample() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
Student student = new Student();
student.setName("Demon222");
student.setSex(1);
student.setId(1);
StudentExample studentExample = new StudentExample();
Criteria criteria = studentExample.createCriteria();
criteria.andIdEqualTo(30);
int result = studentMapper.updateByExample(student,studentExample);
System.out.println(result);
}
updateByExampleSelective,主要区别于updateByExample的是设置项可以为空,当为空时,不改变原有值,应用比较广泛。
@Test
public void testUpdateByExampleSelective() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
Student student = new Student();
student.setName("Demon333");
student.setSex(1);
StudentExample studentExample = new StudentExample();
Criteria criteria = studentExample.createCriteria();
criteria.andIdEqualTo(30);
int result = studentMapper.updateByExampleSelective(student,studentExample);
System.out.println(result);
}
updateByPrimaryKey,通过主键更新,可以直接创建新对象进行更新,但是数据库中不能为空的值,一定要设置,不然会报错。也可以先通过主键获取对象,修改之后再更新。建议使用后者。
@Test
public void testUpdateByPrimaryKey() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
Student student = studentMapper.selectByPrimaryKey(22);
student.setName("Demon555");
student.setSex(1);
int result = studentMapper.updateByPrimaryKey(student);
System.out.println(result);
}
updateByPrimaryKeySelective,而与updateByPrimaryKey不同的是,他只会更新含有数据的属性,对于为空的属性,不予以处理,这样的话如果数据库中设置有默认值,就不会被空值覆盖。
@Test
public void testUpdateByPrimaryKeySelective() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
Student student = studentMapper.selectByPrimaryKey(22);
student.setName("Demon666");
student.setSex(1);
int result = studentMapper.updateByPrimaryKeySelective(student);
System.out.println(result);
}
3.5. 删除接口使用
deleteByExample,根据筛选条件,删除对象。返回值为删除对象个数。
@Test
public void testDeleteByExample() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
StudentExample studentExample = new StudentExample();
//添加条件把模糊查询Demon的数据全部删除
Criteria criteria = studentExample.createCriteria();
criteria.andNameLike("%Demon%");
int result = studentMapper.deleteByExample(studentExample);
System.out.println(result);
}
deleteByPrimaryKey,根据主键删除对象,如果没有对应主键,返回为0;否在返回为1。
@Test
public void testDeleteByPrimaryKey() {
StudentMapper studentMapper = context.getBean(StudentMapper.class);
int result = studentMapper.deleteByPrimaryKey(2);
System.out.println(result);
}
文档下载地址:
https://wenku.baidu.com/view/a7f30fc8961ea76e58fafab069dc5022aaea466b
网友评论