Mybatis-Plus官网
mybatis优势:
JPA优势:
mybatis劣势:
1、如果Mybatis Plus是扳手,那Mybatis Generator就是生产扳手的工厂。
通俗来讲——
MyBatis:一种操作数据库的框架,提供一种Mapper类,支持让你用java代码进行增删改查的数据库操作,省去了每次都要手写sql语句的麻烦。但是!有一个前提,你得先在xml中写好sql语句,是不是很麻烦?于是有下面的:
Mybatis Generator:自动为Mybatis生成简单的增删改查sql语句的工具,省去一大票时间,两者配合使用,开发速度快到飞起。至于标题说的
Mybatis Plus:国人团队苞米豆在Mybatis的基础上开发的框架,在Mybatis基础上扩展了许多功能,荣获了2018最受欢迎国产开源软件第5名,当然也有配套的↓
Mybatis Plus Generator:同样为苞米豆开发,比Mybatis Generator更加强大,支持功能更多,自动生成Entity、Mapper、Service、Controller等
总结:
数据库框架:Mybatis Plus > Mybatis
代码生成器:Mybatis Plus Generator > Mybatis Generator
2、Mybatis-Plus是一个Mybatis的增强工具,它在Mybatis的基础上做了增强,却不做改变。我们在使用Mybatis-Plus之后既可以使用Mybatis-Plus的特有功能,又能够正常使用Mybatis的原生功能。Mybatis-Plus(以下简称MP)是为简化开发、提高开发效率而生,但它也提供了一些很有意思的插件,比如SQL性能监控、乐观锁、执行分析等。
Mybatis虽然已经给我们提供了很大的方便,但它还是有不足之处,实际上没有什么东西是完美的,MP的存在就是为了稍稍弥补Mybatis的不足。在我们使用Mybatis时会发现,每当要写一个业务逻辑的时候都要在DAO层写一个方法,再对应一个SQL,即使是简单的条件查询、即使仅仅改变了一个条件都要在DAO层新增一个方法,针对这个问题,MP就提供了一个很好的解决方案,之后我会进行介绍。另外,MP的代码生成器也是一个很有意思的东西,它可以让我们避免许多重复性的工作。
3、MP的宗旨是简化开发,但是它在提供方便的同时却容易造成代码层次混乱,我们可能会把大量数据逻辑写到service层甚至contoller层中,使代码难以阅读。凡事过犹不及,在使用MP时一定要做分析,不要将所有数据操作都交给MP去实现。毕竟MP只是mybatis的增强工具,它并没有侵入mybatis的原生功能,在使用MP的增强功能的同时,原生mybatis的功能依然是可以正常使用的。
#创建用户表
CREATE TABLE user (
id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键',
name VARCHAR(30) DEFAULT NULL COMMENT '姓名',
age INT(11) DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
manager_id BIGINT(20) DEFAULT NULL COMMENT '直属上级id',
create_time DATETIME DEFAULT NULL COMMENT '创建时间',
CONSTRAINT manager_fk FOREIGN KEY (manager_id)
REFERENCES user (id)
) ENGINE=INNODB CHARSET=UTF8;
#初始化数据:
INSERT INTO user (id, name, age, email, manager_id, create_time)
VALUES (1087982257332887553, '大boss', 40, '[email protected]', NULL, '2019-01-11 14:20:20'),
(1088248166370832385, '王天风', 25, '[email protected]', 1087982257332887553, '2019-02-05 11:12:22'),
(1088250446457389058, '李艺伟', 28, '[email protected]', 1088248166370832385, '2019-02-14 08:31:16'),
(1094590409767661570, '张雨琪', 31, '[email protected]', 1088248166370832385, '2019-01-14 09:15:15'),
(1094592041087729666, '刘红雨', 32, '[email protected]', 1088248166370832385, '2019-01-14 09:48:16');
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
<version>2.0.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.54version>
dependency>
insert()
@TableName(“user”)
@TableId
@TableField(“name”)
使用场景:实体类中添加一些属性只是用于数据传输,不是表中的任何字段
实体类:
package com.project.plan.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户
*
* @author
* @create 2019-08-09 22:21
**/
@ApiModel("用户")
@Data
@TableName("user")
@EqualsAndHashCode(callSuper = true)
public class MyUser extends Model{
//假设将表的主键id改为user_id字段,属性改为userId,mp默认操作id字段,会报错
//只需添加注解到该属性上 @TableId
@ApiModelProperty("用户id")
private Long id;
//指定字段注解,默认是下滑线字段转驼峰属性
@ApiModelProperty("姓名")
@TableField("name")
private String name;
@ApiModelProperty("年龄")
private Integer age;
@ApiModelProperty("邮箱")
private String email;
@ApiModelProperty("直属上级id")
private Long managerId;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("用于数据传输,不和表中的任何字段对应")
@TableField(exist = false)
private String remark;
}
测试类:
package com.project.plan;
import com.project.plan.entity.MyUser;
import com.project.plan.mapper.UserMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
/**
* mybatis-plus测试类
*
* @author
* @create 2019-08-09 22:30
**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class InsertTest {
@Autowired
private UserMapper userMapper;
/**
* 查询
*/
@Test
public void select(){
List<MyUser> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::print);
}
/**
* 测试新增方法
*/
@Test
public void insert(){
MyUser user = new MyUser();
user.setName("张三");
user.setAge(23);
user.setManagerId(1231232122312L);
user.setCreateTime(LocalDateTime.now());
int rows = userMapper.insert(user);
System.out.println("影响记录数:" + rows);
//email属性没有赋值,则sql中不会操作email列
}
}
//sql where id = ?
MyUser user = userMapper.selectById(1231243432L);
System.out.println(JSON.toJSONString(user));
//sql where id in(?,?,?)
List<MyUser> userList = userMapper.selectBatchIds(Arrays.asList(12312312L,43534795348L,45494589L));
System.out.println(JSON.toJSONString(userList));
//sql where age = ? and name = ?
Map<String, Object> columnMap = new HashMap<>(2);
columnMap.put(MyUser.AGE, 23);
columnMap.put(MyUser.NAME, "张三");
userList = userMapper.selectByMap(columnMap);
System.out.println(JSON.toJSONString(userList));
以条件构造器为参数的查询方法
//1、名字中包含雨并且年龄小于40岁
//where name like '%雨%' and age < 40
QueryWrapper wrapper = new QueryWrapper<MyUser>().like(MyUser.NAME, "雨").lt(MyUser.AGE, 40);
List<MyUser> userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//2、名字中包含雨并且年龄大于等于20且小于等于40并且email不为空
//where name like '%雨%' and age between 20 and 40 and email is not null
QueryWrapper<MyUser> wrapper2 = Wrappers.<MyUser>query();
wrapper2.eq(MyUser.NAME, "雨").between(MyUser.AGE, 20, 40).isNotNull(MyUser.EMAIL);
userList = userMapper.selectList(wrapper2);
System.out.println(JSON.toJSONString(userList));
//3、名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序
//where nage like '王%' or age >= 25 order by age desc,id asc
wrapper = new QueryWrapper<MyUser>().likeRight(MyUser.NAME, "王").or().ge(MyUser.AGE, 25)
.orderByDesc(MyUser.AGE).orderByAsc(MyUser.ID);
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//4、创建日期为2019年2月14日并且直属上级姓王
//date_format(create_time, '%Y-%m-%d') and manager_id in(select id from user where name like '王%')
wrapper = new QueryWrapper<MyUser>()
.apply("date_format(create_time, '%Y-%m-%d')={0}", "2019-02-14")
.inSql(MyUser.MANAGER_ID, "select id from user where name like '王%'");
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//5、名字为王姓并且(年龄小于40或邮箱不为空)
//where name like '王%' and (age < 40 or email is not null)
wrapper = Wrappers.<MyUser>query().likeRight(MyUser.NAME, "雨")
.and(mq -> mq.lt(MyUser.AGE, 40).or().isNotNull(MyUser.EMAIL));
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//6、名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空)
//where name like '王%' and (age < 40 and age > 20 and email is not null)
wrapper = Wrappers.<MyUser>query().likeRight(MyUser.NAME, "雨")
.or(mq -> mq.lt(MyUser.AGE, 40).gt(MyUser.AGE, 20).isNotNull(MyUser.EMAIL));
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//7、(年龄小于40或邮箱不为空)并且名字姓王
//(age < 40 or email is not null) and age like '王%'
wrapper = Wrappers.<MyUser>query().nested(qw -> qw.lt(MyUser.AGE, 40).or().isNotNull(MyUser.EMAIL))
.likeRight(MyUser.NAME, "雨");
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//8、年龄为31,33,34
//where age in(31,33,34)
wrapper = Wrappers.<MyUser>query().in(MyUser.AGE, Arrays.asList(31,33,34));
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//9、只返回满足条件的其中一条数据即可
//limit 1
//last中的sql有注入风险
wrapper = Wrappers.<MyUser>query().in(MyUser.AGE, Arrays.asList(31,33,34)).last("limit 1");
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//10、名字中包含雨并且年龄小于40岁 只查询名字,年龄字段
//select name,age from user where name like '%雨%' and age < 40
wrapper = Wrappers.<MyUser>query()
.select(MyUser.NAME, MyUser.AGE)
.like(MyUser.NAME, "雨").lt(MyUser.AGE, 40);
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//11、名字中包含雨并且年龄小于40岁 除了名字,年龄字段不查询,其他字段都要
//select id,email,manager_id,create_time from user where name like '%雨%' and age < 40
wrapper = Wrappers.<MyUser>query()
.like(MyUser.NAME, "雨").lt(MyUser.AGE, 40)
.select(MyUser.class,
info -> !info.getColumn().equals(MyUser.NAME) && !info.getColumn().equals(MyUser.AGE));
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//12、根据姓名、邮箱条件查询user表,不为空才加入条件语句中进行查询
String name = "雨";
String email = "";
wrapper = Wrappers.<MyUser>query();
//原来代码
if (StringUtils.isNotEmpty(name)) {
wrapper.likeRight(MyUser.NAME, name);
}
if (StringUtils.isNotEmpty(email)) {
wrapper.likeRight(MyUser.EMAIL, email);
}
//加入condition后代码
wrapper = Wrappers.<MyUser>query()
.likeRight(StringUtils.isNotEmpty(name), MyUser.NAME, name)
.likeRight(StringUtils.isNotEmpty(email), MyUser.EMAIL, email);
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//13、名字姓张并且年龄小于24岁
//页面一般都是以名字模糊查询,则需要在MyUser类的属性上加注解@TableField(value = "name", condition = SqlCondition.LIKE_RIGHT)
// where name like '张%' and age < 24
MyUser userDto = new MyUser();
userDto.setName("张");
userDto.setAge(24);
wrapper = Wrappers.<MyUser>query(userDto);
//wrapper = new QueryWrapper(userDto);
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//name like '?%'
@ApiModelProperty("姓名")
@TableField(value = "name", condition = SqlCondition.LIKE_RIGHT)
private String name;
//age < ?
@ApiModelProperty("年龄")
@TableField(condition = "%s<<#{%s}")
private Integer age;
//14、名字=张三并且年龄=24
//若map中的value为null,默认拼接的执行sql是: 列名 is null
wrapper = new QueryWrapper<MyUser>();
Map<String, Object> params = new HashMap<>();
params.put(MyUser.NAME, "张三");
params.put(MyUser.AGE, 24);
wrapper.allEq(params);
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//指定若map中有value为null,则拼接的sql中忽略该字段
wrapper.allEq(params, false);
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//allEq加入过滤器 过滤map中的key value都可以
wrapper.allEq((k,v) -> !k.equals(MyUser.EMAIL), params, false);
userList = userMapper.selectList(wrapper);
System.out.println(JSON.toJSONString(userList));
//15、其他使用条件构造器的方法 selectMaps
// 指定返回列,为null的属性不会在json串中出现
wrapper = new QueryWrapper<MyUser>()
.select(MyUser.AGE, MyUser.NAME)
.likeRight(MyUser.NAME, "张")
.lt(MyUser.AGE, 50);
userList = userMapper.selectMaps(wrapper);
System.out.println(JSON.toJSONString(userList));
//按照直属上级分组,查询每组的平均年龄、最大年龄、最小年龄。并且只取年龄总和小于500的组
//select avg(age) avg_age,min(age) min_age, max(age) max_age
//from user group by manager_id having sun(age) < 500
wrapper = new QueryWrapper<MyUser>()
.select("avg(age) avg_age,min(age) min_age, max(age) max_age")
.groupBy(MyUser.MANAGER_ID).having("sum(age) < {0}", 500);
userList = userMapper.selectMaps(wrapper);
System.out.println(JSON.toJSONString(userList));
//17、只返回查询结果的第一列 selectObjs
wrapper = new QueryWrapper<MyUser>()
.select(MyUser.AGE, MyUser.NAME)
.likeRight(MyUser.NAME, "张")
.lt(MyUser.AGE, 50);
List<Object> objects = userMapper.selectObjs(wrapper);
//18、查询总记录数 selectCount
wrapper = new QueryWrapper<MyUser>()
.likeRight(MyUser.NAME, "张")
.lt(MyUser.AGE, 50);
int totalCount = userMapper.selectCount(wrapper);
System.out.println("总记录数:" + totalCount);
//19、单个查询 selectOne (查询到的结果只有1个或者没有,多个则会报错-Except one,but found 2)
wrapper = new QueryWrapper<MyUser>()
.likeRight(MyUser.NAME, "张记")
.eq(MyUser.AGE, 50);
MyUser user = userMapper.selectOne(wrapper);
System.out.println(JSON.toJSONString(user));
//20、 where name like '%雨%' and age >= 24
//lambda条件构造器创建的3中方式
//LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper();
//LambdaQueryWrapper lambdaQueryWrapper2 = new QueryWrapper().lambda();
//lambda中方法引用指定表的列名可以防止误写错误
LambdaQueryWrapper<MyUser> lambda = Wrappers.<MyUser>lambdaQuery();
lambda.eq(MyUser::getName, "雨").ge(MyUser::getAge, 24);
List<Map<String, Object>> result = userMapper.selectMaps(lambda);
System.out.println(JSON.toJSONString(result));
//21、名字为王姓并且(年龄小于40或者邮箱不为空)
//sql where name like '王%' and (age < 40 or email is not null)
lambda = Wrappers.<MyUser>lambdaQuery().like(MyUser::getName, "雨")
.and(lqe -> lqe.lt(MyUser::getAge, 40).or().isNotNull(MyUser::getEmail));
userList = userMapper.selectList(lambda);
System.out.println(JSON.toJSONString(userList));
//22、LambdaQueryChainWrapper 使用 list one count page等方法
List<MyUser> list = new LambdaQueryChainWrapper<MyUser>(userMapper)
.likeRight(MyUser::getName, "雨")
.gt(MyUser::getAge, 20).list();
System.out.println(JSON.toJSONString(list));
mapper类中:
//自定义条件构造器的自定义sql
@Select("select * from user ${ew.customSqlSegment}")
List<MyUser> selectAll(@Param(Constants.WRAPPER) Wrapper<MyUser> wrapper);
测试类:
//23、使用条件构造器的自定义sql
LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<MyUser>()
.likeRight(MyUser::getName, "雨")
.gt(MyUser::getAge, 20);
list = userMapper.selectAll(lambdaQueryWrapper);
System.out.println(JSON.toJSONString(list));
把sql语句写在java类中不太合适,想把sql放入xml文件中,该怎么办呢?
1、先指定mp的xml文件路径:
mybatis-plus.mapper-locations:com/project/plan/resources/mybatis
2、把sql语句放入xml文件中 parameterType=MyUser ,执行结果和上面的一样
<select id="selectAll" parameterType="com.project.plan.entity.MyUser">
select * from user ${ew.customSqlSegMent}
select>
//24、mp分页
Integer pageNo = 1;
Integer pageSize = 10;
//Page page = new Page(pageNo, pageSize); 默认查询总记录数
//Page page = new Page(pageNo, pageSize, false); 不查询总记录数
Page<MyUser> page = new Page<MyUser>(pageNo,pageSize);
QueryWrapper<MyUser> pageWrapper = new QueryWrapper<MyUser>()
.like(MyUser.NAME, "雨").gt(MyUser.AGE, 20);
IPage<MyUser> iPage = userMapper.selectPage(page, pageWrapper);
iPage.getTotal();//数据总条数
iPage.getRecords();//所有数据集合List
iPage.getPages();//总页数
iPage.getCurrent();//当前页码
iPage.getSize();//每页条数
IPage<Map<String, Object>> mapIPage = userMapper.selectMapsPage(page, wrapper);
mapIPage.getTotal();
mapIPage.getRecords();//所有数据集合List
mapIPage.getPages();
mapIPage.getCurrent();
mapIPage.getSize();
自定义sql:
接口定义:
//25、自定义分页
IPage<MyUser> selectUserPage(IPage<MyUser> iPage, @Param(Constants.WRAPPER) Wrapper<MyUser> wrapper);
xml文件中:
<select id="selectUserPage" parameterType="com.project.plan.entity.MyUser">
select * from user ${ew.customSqlSegMent}
select>
//26、修改 update user set name='里斯',age=27 where id=12456456;
MyUser myUser = new MyUser();
myUser.setId(12456456L);
myUser.setName("里斯");
myUser.setAge(27);
int row = userMapper.updateById(myUser);
System.out.println("修改数量:" + row);
//27、update user set name='里斯',age=27 where name='张三' and email='[email protected]'
myUser = new MyUser();
myUser.setName("里斯");
myUser.setAge(27);
int count = userMapper.update(myUser,
new UpdateWrapper<MyUser>()
.eq(MyUser.NAME, "张三").eq(MyUser.EMAIL, "[email protected]")
);
//下面代码效果等同于上面代码效果
//MyUser whereUser = new MyUser();
//whereUser.setName("张三");
//whereUser.setEmail("[email protected]");
//int count = userMapper.update(myUser, new UpdateWrapper(whereUser));
System.out.println("影响行数:" + count);
//28、当修改很多列的时候当然传入实体类更方便,但是就修改一两个列就没必要非new一个对象了 使用set
//update user set name='迪丽热巴' where id=454656565;
int updateCount = userMapper.update(null,
new UpdateWrapper<MyUser>().eq(MyUser.ID, 454656565L).set(MyUser.NAME,"迪丽热巴"));
System.out.println("影响行数:" + updateCount);
//29、使用LambdaUpdateWrapper 修改
//update user set name='迪丽热巴' where id=454656565;
updateCount = userMapper.update(null, new LambdaUpdateWrapper<MyUser>()
.eq(MyUser::getId, 454656565L).set(MyUser::getName, "迪丽热巴"));
System.out.println("影响行数:" + updateCount);
//30、使用LambdaUpdateChainWrapper 修改
//update user set name='迪丽热巴' where id=454656565;
boolean updateSuccess = new LambdaUpdateChainWrapper<MyUser>(userMapper)
.eq(MyUser::getId, 454656565L).set(MyUser::getName, "迪丽热巴").update();
System.out.println("更新成功:" + updateSuccess);
//删除 deleteById、deleteBatchIds、deleteByMap
int rows = userMapper.deleteById(454656565L);
//where id in(?,?,?)
rows = userMapper.deleteBatchIds(Arrays.asList(454656565L, 484656565L, 554656565L));
Map<String, Object> columnMap = new HashMap<>();
//delete from user where name='张三' and age=26;
columnMap.put(MyUser.NAME, "张三");
columnMap.put(MyUser.AGE, 26);
rows = userMapper.deleteByMap(columnMap);
//使用条件构造器删除
LambdaQueryWrapper lambdaQueryWrapper1 = Wrappers.<MyUser>lambdaQuery()
.eq(MyUser::getManagerId, 3453454L)
.or().gt(MyUser::getAge, 50);
rows = userMapper.delete(lambdaQueryWrapper1);
System.out.println("删除的条数:" + rows);
在Mybatis-Plus中提供了ActiveRecord的模式,支持 ActiveRecord 形式调用,实体类只需继承 Model 类,Mapper接口继承 BaseMapper 即可实现基本 CRUD 操作,简单来说就是一个实体类继承Model类,并通过注解与数据库的表名进行关联,这样就可以通过实体类直接进行表的简单增删改查操作,这样也确实极大的方便了开发人员
//ActiveRecord模式 新增或修改
MyUser arUser = new MyUser();
arUser.setName("李海");
arUser.setEmail("[email protected]");
arUser.insertOrUpdate();
//update user set name='利达' and age=23 where id=2342343243;
MyUser updateUser = new MyUser();
updateUser.setName("利达");
updateUser.setAge(23);
arUser.update(new LambdaQueryWrapper<MyUser>().eq(MyUser::getId, 2342343243L).setEntity(updateUser));
//假设将表的主键id改为user_id字段,属性改为userId,mp默认操作id字段,会报错
//只需添加注解到该属性上 @TableId
@ApiModelProperty("用户id")
@TableId(type = IdType.AUTO)
/**
* AUTO(0),//数据库自增 依赖数据库
* NONE(1),// 表示该类型未甚至主键类型 (如果没有主键策略)默认根据雪花算法生成
* INPUT(2),//用户输入ID(该类型可以通过自己注册填充插件进行填充)
* //下面这三种类型,只有当插入对象id为空时 才会自动填充。
* ID_WORKER(3),//全局唯一(idWorker)数值类型
* UUID(4),//全局唯一(UUID)
* ID_WORKER_STR(5);//全局唯一(idWorker的字符串表示)
*/
private Long id;
mybatis-plus.mapper-locations=classpath:mybatis/*.xml
#mybatis-plus.global-config.db-config.table-prefix=mp_
mybatis-plus.global-config.db-config.id-type=uuid
mybatis-plus.type-aliases-package=com.project.plan.entity
mybatis-plus.configuration.map-underscore-to-camel-case=true
#mybatis-plus.config-location=classpath:mybatis-config.xml
这个在实际开发中使用很多
service接口:
package com.project.plan.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.project.plan.entity.MyUser;
public interface IMyUserService extends IService<MyUser> {
}
service接口业务实现类:
package com.project.plan.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.plan.entity.MyUser;
import com.project.plan.mapper.UserMapper;
import com.project.plan.service.IMyUserService;
import org.springframework.stereotype.Service;
/**
* 用户实现类
*
* @author
* @create 2019-08-10 15:09
**/
@Service
public class IMyUserServiceImpl extends ServiceImpl<UserMapper, MyUser> implements IMyUserService {
}
测试类使用:
@Autowired
private IMyUserService userService;
@Test
public void testServiceImpl(){
//userService.getOne
MyUser user = userService.getOne(new LambdaQueryWrapper<MyUser>().likeRight(MyUser::getName, "李"));
System.out.println(JSON.toJSONString(user));
//list()
List<MyUser> userList = userService.lambdaQuery().gt(MyUser::getAge, 26).list();
System.out.println(JSON.toJSONString(userList));
//userService.getMap
Map<String, Object> mapData = userService.getMap(new QueryWrapper<MyUser>().lt(MyUser.AGE, 30));
System.out.println(JSON.toJSONString(mapData));
//userService.saveOrUpdateBatch
List<MyUser> list = new ArrayList<>();
MyUser user1 = new MyUser();
user1.setName("了解");
user1.setAge(28);
MyUser user2 = new MyUser();
user2.setName("王大陆");
user2.setAge(29);
list.add(user1);
list.add(user2);
boolean result = userService.saveOrUpdateBatch(list);
System.out.println(result);
//userService.lambdaUpdate()
userService.lambdaUpdate().eq(MyUser::getAge, 24)
.set(MyUser::getAge, 25).set(MyUser::getManagerId, 232352353L);
//remove delete from user where id=23423423423
userService.lambdaUpdate().eq(MyUser::getId, 23423423423L).remove();
}