MyBatis-Plus (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
引入maven依赖
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.0version>
dependency>
yml配置
server:
port: 8090
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/user?serverTimezone=UTC
username: root
password: etoak
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启sql日志
call-setters-on-nulls: true
map-underscore-to-camel-case: true
主启动类
@MapperScan("com.enbei.mapper")
@SpringBootApplication
public class App {
public static void main( String[] args ) {
SpringApplication.run(App.class,args);
}
}
分页插件
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setDbType(DbType.MYSQL);
paginationInnerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
创建实体
@Data
@TableName("user")
@NoArgsConstructor
@AllArgsConstructor
public class User {
/**
* ID
*/
@TableId
private Long id;
/**
* 用户名
*/
private String userName;
/**
* 年龄
*/
private Integer age;
/**
* 邮箱
*/
private String email;
}
关于Mybatis-plus注解
mapper接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
service
@Service
public class UserService {
@Resource
private UserMapper userMapper;
//添加数据
public void insert() {
User user = new User();
user.setUserName("elena");
user.setAge(21);
user.setEmail("[email protected]");
userMapper.insert(user);
}
//根据id查询
public void selectById() {
userMapper.selectById(1);
}
//根据id更新
public void updateById(){
// 先查询
User user = userMapper.selectById(1);
user.setUserName("Jennie");
// 再修改
int result = userMapper.updateById(user);
System.out.println(result);
}
//根据map更新
public void selectByMap(){
Map<String,Object> map = new HashMap<>();
map.put("age",25);
List<User> users = userMapper.selectByMap(map);
}
//根据ID批量查询
public void selectBatchIds() {
List<User> employees = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
employees.forEach(System.out::println);
}
//根据ID删除
public void deleteById() {
userMapper.deleteById(1);
}
//根据ID批量删除
public void deleteBatchIds() {
userMapper.deleteBatchIds(Arrays.asList(4, 5, 6));
}
}
通用service
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
}
如果有接口的话
public interface IUserService extends IService<User> {}
service
@Service
public class TestService {
@Resource
private UserService userService;
public void save(){
User user = new User();
user.setUserName("jack");
user.setAge(22);
user.setEmail("[email protected]");
userService.save(user);
}
public void saveBatch(){
User user1 = new User();
user1.setUserName("jack");
user1.setAge(22);
user1.setEmail("[email protected]");
User user2 = new User();
user2.setUserName("elena");
user2.setAge(23);
user2.setEmail("[email protected]");
List<User> list = new ArrayList();
Collections.addAll(list,user1,user2);
userService.saveBatch(list);
}
public void saveOrUpdate(){
User user = new User();
user.setId(1658731091639959553L);
user.setUserName("jack");
user.setAge(100);
user.setEmail("[email protected]");
userService.saveOrUpdate(user);
//userService.saveOrUpdateBatch(Collection entityList); 与saveBatch用法一致
}
public void removeById(){
userService.removeById(1658731091639959553L);
}
public void removeByIds(){
userService.removeByIds(Arrays.asList(1, 2, 3));
}
public void removeByMap(){
Map<String,Object> map = new HashMap<>();
map.put("age",25);
userService.removeByMap(map);
}
public void updateById(){
User user = new User();
user.setId(1658731091639959553L);
user.setUserName("jack");
user.setAge(101);
user.setEmail("[email protected]");
userService.updateById(user);
}
public void updateBatchById(){
User user1 = new User();
user1.setUserName("jack");
user1.setAge(200);
user1.setEmail("[email protected]");
User user2 = new User();
user2.setUserName("elena");
user2.setAge(200);
user2.setEmail("[email protected]");
List<User> list = new ArrayList();
Collections.addAll(list,user1,user2);
userService.updateBatchById(list);
}
public User getById(){
return userService.getById(1);
}
public List<User> list(){
return userService.list();
}
public List<Map<String, Object>> listMaps(){
return userService.listMaps();
}
public List<User> page(){
int page = 1;
int pageSize = 2;
Page<User> userPage = new Page<>(page, pageSize);
Page<User> result = userService.page(userPage);
result.getTotal();//总记录数
result.getCurrent();//当前页
result.getSize();//每页记录数
result.getPages();//总页数
return userPage.getRecords();
}
public int count(){
return userService.count();
}
}
通用mapper
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
@Resource
private UserMapper userMapper;
//查询单条数据
public User selectOne(String name) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//queryWrapper.eq("user_name","elena");
queryWrapper.eq(!StringUtils.isEmpty(name),"user_name",name);
return userMapper.selectOne(queryWrapper);
// userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,name));
}
//删除
public void delete(String name) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",name);
userMapper.delete(queryWrapper);
// userMapper.delete(Wrappers.lambdaQuery(User.class).eq(User::getUserName,name));
}
//将符合queryWrapper条件的数据更新为实体类中的数据
public void update(String name) {
User user = userMapper.selectById(1);
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("user_name",name);
// LambdaUpdateWrapper lambdaUpdateWrapper = Wrappers.lambdaUpdate(User.class).eq(User::getUserName, name);
if (user != null){
user.setAge(10086);
userMapper.update(user,updateWrapper);
// userMapper.update(user,lambdaUpdateWrapper);
}
}
//分页
public List<User> pageList(String name) {
int page = 1;
int pageSize = 2;
Page<User> userPage = new Page<>(page, pageSize);
LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery(User.class)
.like(User::getUserName, name)
.eq(User::getAge,23)
.orderByDesc(User::getId);//根据id排序
Page<User> result = userMapper.selectPage(userPage, lambdaQueryWrapper);
result.getTotal();//总记录数
result.getCurrent();//当前页
result.getSize();//每页记录数
result.getPages();//总页数
return userPage.getRecords();
}
}
通用service
@Service
public class TestService{
@Resource
private UserService userService;
//查询
public void lambdaQuery(){
List<User> list = userService.lambdaQuery().eq(User::getAge, 18).list();
list.forEach(System.out::println);
}
//修改
public void lambdaUpdate(){
boolean update = userService.lambdaUpdate().eq(User::getAge, 18).set(User::getAge, 31).update();
System.out.println(update);
}
//删除
public void lambdaDel(){
boolean remove = userService.lambdaUpdate().eq(User::getAge, 18).remove();
System.out.println(remove);
}
}
eq(R column, Object val)
eq(boolean condition, R column, Object val)
eq("name", "老王")
—>name = '老王'
ne(R column, Object val)
ne(boolean condition, R column, Object val)
ne("name", "老王")
—>name <> '老王'
gt(R column, Object val)
gt(boolean condition, R column, Object val)
gt("age", 18)
—>age > 18
ge(R column, Object val)
ge(boolean condition, R column, Object val)
ge("age", 18)
—>age >= 18
lt(R column, Object val)
lt(boolean condition, R column, Object val)
lt("age", 18)
—>age < 18
le(R column, Object val)
le(boolean condition, R column, Object val)
le("age", 18)
—>age <= 18
between(R column, Object val1, Object val2)
between(boolean condition, R column, Object val1, Object val2)
between("age", 18, 30)
—>age between 18 and 30
notBetween(R column, Object val1, Object val2)
notBetween(boolean condition, R column, Object val1, Object val2)
notBetween("age", 18, 30)
—>age not between 18 and 30
like(R column, Object val)
like(boolean condition, R column, Object val)
like("name", "王")
—>name like '%王%'
notLike(R column, Object val)
notLike(boolean condition, R column, Object val)
notLike("name", "王")
—>name not like '%王%'
likeLeft(R column, Object val)
likeLeft(boolean condition, R column, Object val)
likeLeft("name", "王")
—>name like '%王'
likeRight(R column, Object val)
likeRight(boolean condition, R column, Object val)
likeRight("name", "王")
—>name like '王%'
notLikeLeft(R column, Object val)
notLikeLeft(boolean condition, R column, Object val)
notLikeLeft("name", "王")
—>name not like '%王'
notLikeRight(R column, Object val)
notLikeRight(boolean condition, R column, Object val)
notLikeRight("name", "王")
—>name not like '王%'
isNull(R column)
isNull(boolean condition, R column)
isNull("name")
—>name is null
isNotNull(R column)
isNotNull(boolean condition, R column)
isNotNull("name")
—>name is not null
in(R column, Collection<?> value)
in(boolean condition, R column, Collection<?> value)
in("age",{1,2,3})
—>age in (1,2,3)
in(R column, Object... values)
in(boolean condition, R column, Object... values)
in("age", 1, 2, 3)
—>age in (1,2,3)
notIn(R column, Collection<?> value)
notIn(boolean condition, R column, Collection<?> value)
notIn("age",{1,2,3})
—>age not in (1,2,3)
notIn(R column, Object... values)
notIn(boolean condition, R column, Object... values)
notIn("age", 1, 2, 3)
—>age not in (1,2,3)
inSql(R column, String inValue)
inSql(boolean condition, R column, String inValue)
inSql("age", "1,2,3,4,5,6")
—>age in (1,2,3,4,5,6)
inSql("id", "select id from table where id < 3")
—>id in (select id from table where id < 3)
notInSql(R column, String inValue)
notInSql(boolean condition, R column, String inValue)
notInSql("age", "1,2,3,4,5,6")
—>age not in (1,2,3,4,5,6)
notInSql("id", "select id from table where id < 3")
—>id not in (select id from table where id < 3)
groupBy(R... columns)
groupBy(boolean condition, R... columns)
groupBy("id", "name")
—>group by id,name
orderByAsc(R... columns)
orderByAsc(boolean condition, R... columns)
orderByAsc("id", "name")
—>order by id ASC,name ASC
orderByDesc(R... columns)
orderByDesc(boolean condition, R... columns)
orderByDesc("id", "name")
—>order by id DESC,name DESC
orderBy(boolean condition, boolean isAsc, R... columns)
orderBy(true, true, "id", "name")
—>order by id ASC,name ASC
having(String sqlHaving, Object... params)
having(boolean condition, String sqlHaving, Object... params)
having("sum(age) > 10")
—>having sum(age) > 10
having("sum(age) > {0}", 11)
—>having sum(age) > 11
func(Consumer<Children> consumer)
func(boolean condition, Consumer<Children> consumer)
func(i -> if(true) {i.eq("id", 1)} else {i.ne("id", 1)})
or()
or(boolean condition)
拼接 OR
注意事项:
主动调用or
表示紧接着下一个方法不是用and
连接!(不调用or
则默认为使用and
连接)
例: eq("id",1).or().eq("name","老王")
—>id = 1 or name = '老王'
or(Consumer<Param> consumer)
or(boolean condition, Consumer<Param> consumer)
or(i -> i.eq("name", "李白").ne("status", "活着"))
—>or (name = '李白' and status <> '活着')
and(Consumer<Param> consumer)
and(boolean condition, Consumer<Param> consumer)
and(i -> i.eq("name", "李白").ne("status", "活着"))
—>and (name = '李白' and status <> '活着')
nested(Consumer<Param> consumer)
nested(boolean condition, Consumer<Param> consumer)
nested(i -> i.eq("name", "李白").ne("status", "活着"))
—>(name = '李白' and status <> '活着')
apply(String applySql, Object... params)
apply(boolean condition, String applySql, Object... params)
拼接 sql
注意事项:
该方法可用于数据库函数 动态入参的params
对应前面applySql
内部的{index}
部分.这样是不会有sql注入风险的,反之会有!
例: apply("id = 1")
—>id = 1
例: apply("date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
—>date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
例: apply("date_format(dateColumn,'%Y-%m-%d') = {0}", "2008-08-08")
—>date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
last(String lastSql)
last(boolean condition, String lastSql)
无视优化规则直接拼接到 sql 的最后
注意事项:
只能调用一次,多次调用以最后一次为准 有sql注入的风险,请谨慎使用
例: last("limit 1")
exists(String existsSql)
exists(boolean condition, String existsSql)
exists("select id from table where age = 1")
—>exists (select id from table where age = 1)
notExists(String notExistsSql)
notExists(boolean condition, String notExistsSql)
notExists("select id from table where age = 1")
—>not exists (select id from table where age = 1)