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/**
public interface baseMapper extends Mapper, MySqlMapper {
}
在mbg.xml文件中添加tkMapper插件:
生成器代码
这里还是跟之前的一致,不需要改变, 直接运行,会生成实体类,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{ //我们可以自定义我们的方法 }
体验一下tkMapper提供的方法:
@Resource
private UserMapper userMapper;
@Test
public void testAll(){
//查询用户所有数据
List 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 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 users = userMapper.selectByExample(example);
users.stream().forEach(System.out::println);
}



