逆向工程
- MyBatis Generator,简称MBG, 是一个专为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询,但是表连接,存储过程等这些复杂sql的定义需要我们手工编写
- 官方文档地址: http://www.mybatis.org/generator/
- 官方工程地址: https://github.com/mybatis/generator/releases
在application.yml文件中配置mybatis:
spring:
# datasource 数据源配置内容
datasource:
url: jdbc:mysql://localhost:3306/learn_mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
mvc:
static-path-pattern: /**
resources:
static-locations: classpath:/resources/,classpath:/static/,classpath:/templates/
# mybatis 配置内容
mybatis:
config-location: classpath:mybatis-config.xml # 配置 MyBatis 配置文件路径
mapper-locations: classpath:mapper/**/*.xml # 配置 Mapper XML 地址
type-aliases-package: com.example.springboot_mybatis.model # 配置数据库实体包路径
logging:
level:
com.example.springboot_mybatis.mapper: debug
工程结构:
添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 使用 MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 实现对 MyBatis 的自动化配置 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!-- MyBatis逆向工程, 逆向工程主要使用这个依赖 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
<!-- tkMapper, 后面拓展会用到-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.0.3</version>
</dependency>
</dependencies>
配置文件
mbg.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">
<!-- 实现序列化 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<!-- 实现tostring,但是包含hash值还有序列的id -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- 阻止生成自动注释, 反向代理生成的注释不太美观,还不如不注释-->
<commentGenerator>
<property name="javaFileEncoding" value="UTF-8"/>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/learn_mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"
userId="root"
password="123456">
</jdbcConnection>
<!-- 类转换器信息 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 实体类生成位置 -->
<javaModelGenerator targetPackage="com.example.springboot_mybatis.model" targetProject="D:\java\idea\workspace\springboot\springboot_mybatis\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- xml生成位置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="D:\java\idea\workspace\springboot\springboot_mybatis\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- dao生成位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.springboot_mybatis.mapper" targetProject="D:\java\idea\workspace\springboot\springboot_mybatis\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 生成的表,以及实体类命名, 这里多了几个属性,主要是阻止生成example类(用不到)
tableName : 数据库表名
enableCountByExample : 是否生成查询总数的 Example
enableDeleteByExample : 是否生成删除的 Example
enableSelectByExample : 是否生成查询集合的 Example
enableUpdateByExample : 是否生成修改的 Example
-->
<table tableName="t_role" domainObjectName="Role" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
生成器代码
public class Generator {
public static void main(String[] args) {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File(Generator.class.getClassLoader().getResource("mbg.xml").getFile());
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = null;
try {
config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用tkMapper
通过引入第三方插件,可以使开发更加的美观,高效
添加依赖
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.0.3</version>
</dependency>
配置文件
这里呢,我们首先得创建BaseMapper:
- 注意:
这个基础mapper不能和其他mapper放到同一包下
,不然会有异常:java.lang.ClassCastException:sun.reflect.generocs.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
/**
* 基础Mapper
*/
public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
在mbg.xml文件中添加tkMapper插件:
<!-- 集成tkMapper -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<!-- 这里配置我们刚才创建的基础mapper -->
<property name="mappers" value="com.example.springboot_mybatis.config.BaseMapper" />
<!--caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true-->
<property name="caseSensitive" value="true"/>
</plugin>
生成器代码
这里还是跟之前的一致,不需要改变, 直接运行,会生成实体类,mapper接口和xml文件
简单使用
- springboot项目中使用Mapper的时候,发现又出现了一个bug:
tk.mybatis.mapper.MapperException: 无法获取实体类对应的表明
,原因是启动类@MapperScan注解要导入itk.mybatis.spring.annotation.MapperScan;不要使用org.mybatis.spring.annotation.MapperScan
来看自动生成的用户mapper,继承了我们创建的BaseMapper -> tkMapper封装好的一些方法(增删改查等),除了基础方法,我们可以添加新的数据库操作
public interface UserMapper extends BaseMapper<User> {
//我们可以自定义我们的方法
}
体验一下tkMapper提供的方法:
@Resource
private UserMapper userMapper;
@Test
public void testAll(){
//查询用户所有数据
List<User> users = userMapper.selectAll();
users.stream().forEach(System.out::println);
}
@Test
public void testGetById(){
//根据主键id查询
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user);
}
@Test
public void testLike(){
//模糊查询
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
criteria.andLike("username", "%陈%");
List<User> users = userMapper.selectByExample(example);
users.stream().forEach(System.out::println);
}
@Test
public void testEqual(){
//查询用户名为cyz的数据
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("username", "cyz");
List<User> users = userMapper.selectByExample(example);
users.stream().forEach(System.out::println);
}