目录
1、了解Mybatis-Plus
1.1、Mybatis-Plus介绍
1.2、代码以及文档
1.3、特性
1.4、架构
2、快速开始
2.1、创建数据库以及表
2.2.1 创建主工程
2.2.2 导入依赖:
2.3、Mybatis + MP
2.3.1、创建子Module
2.3.2、Mybatis实现查询User
2.3.3、Mybatis+MP实现查询User
2.4、Spring + Mybatis + MP
2.4.1、创建子Module
2.4.2、实现查询User
2.5、SpringBoot + Mybatis + MP
2.5.1、创建工程
2.5.2、导入依赖
2.5.3、编写application.properties
2.5.4、编写pojo
2.5.5、编写mapper
2.5.6、编写启动类
2.5.7、编写测试用例
3、通用CRUD
3.1 方法源代码
3.2 BaseMapper方法实现
4、配置
4.1、基本配置
4.1.1、configLocation
4.1.2、mapperLocations
4.1.3、typeAliasesPackage
4.2、进阶配置
4.2.1、mapUnderscoreToCamelCase
4.2.2、cacheEnabled
4.3、DB 策略配置
4.3.1、idType
4.3.2、tablePrefix
4.4 spring中的配置
5、条件构造器
5.1、allEq
5.2、基本比较操作
5.3、模糊查询
5.4、排序
5.5、逻辑查询
5.6、选择列输出select
对于Mybatis整合MP有常常有三种用法,分别是Mybatis+MP、Spring+Mybatis+MP、Spring Boot+Mybatis+MP。
-- 创建测试表
CREATE TABLE `tb_user`
(
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_name` varchar(20) NOT NULL COMMENT '用户名',
`password` varchar(20) NOT NULL COMMENT '密码',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- 插入测试数据
INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`)
VALUES ('1', 'zhangsan', '123456', '张三', '18', '[email protected]');
INSERT
INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`)
VALUES ('2', 'lisi', '123456', '李四', '20', '[email protected]');
INSERT
INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`)
VALUES ('3', 'wangwu', '123456', '王五', '28', '[email protected]');
INSERT
INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`)
VALUES ('4', 'zhaoliu', '123456', '赵六', '21', '[email protected]');
INSERT
INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`)
VALUES ('5', 'sunqi', '123456', '孙七', '24', '[email protected]');
2.2、创建工程
GroupId:cn.awen.mq
ArtifactId: mybatis-plus
Version: 1.0.SNAPSHOP
com.baomidou
mybatis-plus
3.1.1
mysql
mysql-connector-java
5.1.47
com.alibaba
druid
1.0.11
org.projectlombok
lombok
true
1.18.4
junit
junit
4.12
org.slf4j
slf4j-log4j12
1.6.4
org.apache.maven.plugins
maven-compiler-plugin
1.8
创建配置文件(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=[%t] [%c]-[%p] %m%n
@Data//生成get和set方法
@NoArgsConstructor//生成无参数构造方法
@AllArgsConstructor//生成全参数构造方法
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
第三步,编写UserMapper接口
public interface UserMapper {
List findAll();
}
第四步,编写UserMapper.xml文件
第五步,编写TestMybatis测试用例
public class TestMybatis {
@Test
public void testFindAll() throws Exception{
String config = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(config);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//测试查询
List users = userMapper.findAll();
for (User user : users) {
System.out.println(user);
}
}
}
public interface UserMapper extends BaseMapper {
List findAll();
}
public class TestMybatisPlus {
@Test
public void testFindAll() throws Exception{
String config = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(config);
SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//测试查询
// List users = userMapper.findAll();
List users = userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}
解决:在User对象中添加@TableName,指定数据库表名
简单说明
在pom导入maven依赖
5.1.6.RELEASE
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-test
${spring.version}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
jdbc.username=root
jdbc.password=root
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestMybatisSpring {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList(){
List users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
true
com.baomidou
mybatis-plus-boot-starter
3.1.1
mysql
mysql-connector-java
5.1.47
org.slf4j
slf4j-log4j12
org.springframework.boot
spring-boot-maven-plugin
创建配置文件(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=[%t] [%c]-[%p] %m%n
spring.application.name = itcast-mp-springboot
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
@Data//生成get和set方法
@NoArgsConstructor//生成无参数构造方法
@AllArgsConstructor//生成全参数构造方法
@TableName("tb_user")
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
public interface UserMapper extends BaseMapper {
User findById(Long id);
}
@SpringBootApplication
@MapperScan("cn.itcast.mp.mapper") //设置mapper接口的扫描包
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TestMybatisSpringBoot {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList(){
List users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}
public interface BaseMapper extends Mapper {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper wrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List selectBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List selectByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestUserMapper {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert() {
User user = new User();
user.setMail("[email protected]");
user.setAge(31);
user.setUserName("caocao");
user.setName("曹操");
user.setPassword("123456");
user.setAddress("北京");
int result = this.userMapper.insert(user); //result数据库受影响的行数
System.out.println("result => " + result);
//获取自增长后的id值, 自增长后的id值会回填到user对象中
System.out.println("id => " + user.getId());
}
@Test
public void testDeleteById(){
// 根据id删除数据
int result = this.userMapper.deleteById(9L);
System.out.println("result => " + result);
}
@Test
public void testDeleteByMap(){
Map map = new HashMap<>();
map.put("user_name", "zhangsan");
map.put("password", "999999");
// 根据map删除数据,多条件之间是and关系
int result = this.userMapper.deleteByMap(map);
System.out.println("result => " + result);
}
@Test
public void testDelete(){
//用法一:
// QueryWrapper wrapper = new QueryWrapper<>();
// wrapper.eq("user_name", "caocao")
// .eq("password", "123456");
//用法二:
User user = new User();
user.setPassword("123456");
user.setUserName("caocao");
QueryWrapper wrapper = new QueryWrapper<>(user);
// 根据包装条件做删除
int result = this.userMapper.delete(wrapper);
System.out.println("result => " + result);
}
@Test
public void testDeleteBatchIds(){
// 根据id批量删除数据
int result = this.userMapper.deleteBatchIds(Arrays.asList(10L, 11L));
System.out.println("result => " + result);
}
@Test
public void testSelectById() {
User user = this.userMapper.selectById(2L);
System.out.println(user);
}
@Test
public void testUpdateById() {
User user = new User();
user.setId(1L); //条件,根据id更新
user.setAge(19); //更新的字段
user.setPassword("666666");
int result = this.userMapper.updateById(user);
System.out.println("result => " + result);
}
@Test
public void testUpdate() {
User user = new User();
user.setAge(20); //更新的字段
user.setPassword("8888888");
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("user_name", "zhangsan"); //匹配user_name = zhangsan 的用户数据
//根据条件做更新
int result = this.userMapper.update(user, wrapper);
System.out.println("result => " + result);
}
@Test
public void testUpdate2() {
UpdateWrapper wrapper = new UpdateWrapper<>();
wrapper.set("age", 21).set("password", "999999") //更新的字段
.eq("user_name", "zhangsan"); //更新的条件
//根据条件做更新
int result = this.userMapper.update(null, wrapper);
System.out.println("result => " + result);
}
@Test
public void testSelectBatchIds(){
// 根据id批量查询数据
List users = this.userMapper.selectBatchIds(Arrays.asList(2L, 3L, 4L, 100L));
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testSelectOne(){
QueryWrapper wrapper = new QueryWrapper<>();
//查询条件
wrapper.eq("password", "123456");
// 查询的数据超过一条时,会抛出异常
User user = this.userMapper.selectOne(wrapper);
System.out.println(user);
}
@Test
public void testSelectCount(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.gt("age", 20); // 条件:年龄大于20岁的用户
// 根据条件查询数据条数
Integer count = this.userMapper.selectCount(wrapper);
System.out.println("count => " + count);
}
@Test
public void testSelectList(){
QueryWrapper wrapper = new QueryWrapper<>();
//设置查询条件
wrapper.like("email", "itcast");
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
// 测试分页查询
@Test
public void testSelectPage(){
Page page = new Page<>(3,1); //查询第一页,查询1条数据
QueryWrapper wrapper = new QueryWrapper<>();
//设置查询条件
wrapper.like("email", "itcast");
IPage iPage = this.userMapper.selectPage(page, wrapper);
System.out.println("数据总条数: " + iPage.getTotal());
System.out.println("数据总页数: " + iPage.getPages());
System.out.println("当前页数: " + iPage.getCurrent());
List records = iPage.getRecords();
for (User record : records) {
System.out.println(record);
}
}
}
#指定全局配置文件
mybatis-plus.config-location=classpath:mybatis-config.xml
MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
#指定Mapper.xml文件的路径
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。
#实体对象的扫描包
mybatis-plus.type-aliases-package = cn.itcast.mp.pojo
本部分(Confifiguration)的配置大都为 MyBatis 原生支持的配置,这意味着您可以通过 MyBatis XML 配置文件的形式进行配置。
是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名到经典 Java属性名 aColumn(驼峰命名)的类似映射。
#关闭自动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
#mybatis-plus.configuration.map-underscore-to-camel-case=true
全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为 true。
#禁用缓存
mybatis-plus.configuration.cache-enabled=false
全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。
#全局ID生成策略
mybatis-plus.global-config.db-config.id-type=auto
表名前缀,全局配置后可省略@TableName()配置。
#配置全局表名前缀
mybatis-plus.global-config.db-config.table-prefix=tb_
@Test
public void testAllEq() {
Map params = new HashMap<>();
params.put("name", "李四");
params.put("age", "20");
params.put("password", null);
QueryWrapper wrapper = new QueryWrapper<>();
// 默认情况如果参数为null,则当成条件拼接在where语句之后
//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE password IS NULL AND name = ? AND age = ?
// wrapper.allEq(params);
// 如果第二个参数传false,则在where语句之后不拼接
//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name = ? AND age = ?
// wrapper.allEq(params, false);
// 匹配k指定的值才做拼接
//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE age = ?
// wrapper.allEq((k, v) -> (k.equals("age") || k.equals("id")) , params);
// 匹配k指定的值才做拼接
//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name = ? AND age = ?
wrapper.allEq((k, v) -> (k.equals("age") || k.equals("id") || k.equals("name")), params);
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testEq() {
QueryWrapper wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE password = ? AND age >= ? AND name IN (?,?,?)
wrapper.eq("password", "123456")
.ge("age", 20)
.in("name", "李四", "王五", "赵六");
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
like
notLike
NOT LIKE '%值%'
例: notLike("name", "王") ---> name not like '%王%'
likeLeft
LIKE '%值'
例: likeLeft("name", "王") ---> name like '%王'
likeRight
LIKE '值%'
例: likeRight("name", "王") ---> name like '王%'
@Test
public void testLike() {
QueryWrapper wrapper = new QueryWrapper<>();
// SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name LIKE ?
// 参数:%五(String)
wrapper.likeLeft("name", "五");
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testOrderByAgeDesc() {
QueryWrapper wrapper = new QueryWrapper<>();
// SELECT id,user_name,name,age,email AS mail FROM tb_user ORDER BY age DESC
//按照年龄倒序排序
wrapper.orderByDesc("age");
//按照年龄正序排序
//wrapper.orderByAsc("age");
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
在MP查询中,默认查询所有的字段,如果有需要也可以通过select方法进行指定字段。
@Test
public void testSelect() {
QueryWrapper wrapper = new QueryWrapper<>();
//SELECT id,name,age FROM tb_user WHERE name = ? OR age = ?
wrapper.eq("name", "王五")
.or()
.eq("age", 21)
.select("id", "name", "age"); //指定查询的字段
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}