1.创建项目(mybatisplu)
1.1. 勾选“Lombok”、“spring Web”依赖
1.2. 添加依赖
<!--mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
</dependency>
<!-- mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
1.3. yml文件配置
(1)把properties结尾的文件,改成yml结尾的格式;
(2)添加配置
#项目的端口
server:
port: 8080
#mysql配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mp_db?serverTimezone=UTC
username: root
password: root
#mabatis-plus的配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印sql日志
map-underscore-to-camel-case: true # 是否开启驼峰命名转换
1.4. 创建实体类(含默认值设置)
实体类需要使用@TableName【表名】、@TableId【表中主键】、@TableField【表中字段】注解,将实体类中的字段和数据库表中的字段进行绑定;
(1)@TableName【表名】(可选):用于指定实体类所绑定的表名,此注解是可写可不写注解,为了更加明确实体类绑定的表名,(推荐写上);
(2)@TableId【表中主键】(可选):用于指定实体类中对应表中的主键名,如果主键自增,一定要加上type = IdType.AUTO,此注解是可写可不写注解,为了更明确实体类绑定的主键名,(推荐写上);
(3)@TableField【表中字段】(可选):用于指定实体类属性对应表中的字段:
1)当实体类中的属性名和表中的字段相同,此注解可写可不写(推荐不写);
2)当实体类中的属性名和表中的字段不同时,此注解必写(必写);
package com.example.my_mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* 用户表
*/
@Data
@NoArgsConstructor
@TableName(value = "s_user")
public class User {
/**
* 用户id
*/
@TableId(value = "id", type = IdType.AUTO) //type = IdType.AUTO,表示该字段的值将由数据库自动生成
private Integer id;
/**
* 用户名
*/
@TableField(value = "user_name")
private String userName;
/**
* 用户密码
*/
// @TableField(value = "password")
private String password;
/**
* 性别
*/
// @TableField(value = "sex")
private String sex;
/**
* 手机号
*/
// @TableField(value = "phone")
private String phone;
/**
* 邮箱
*/
// @TableField(value = "email")
private String email;
/**
* 户籍所在地
*/
// @TableField(value = "address")
private String address;
/**
* 工作地
*/
@TableField(value = "work_address")
private Integer workAddress;
/**
* 职业
*/
// @TableField(value = "profession")
private Integer profession;
/**
* 插入时间(fill= FieldFill.INSERT:插入时,默认时间)
*/
@TableField(value = "in_time",fill= FieldFill.INSERT)
private Date inTime;
/**
* 修改时间(fill = FieldFill.INSERT_UPDATE:新增和修改时,默认时间)
*/
@TableField(value = "oper_time",fill = FieldFill.INSERT_UPDATE)
private Date operTime;
/**
* 逻辑删除(0 正常,2 删除)
*/
@TableField(value = "del_flag",fill = FieldFill.INSERT)
private String delFlag;
/**
* 备注
*/
// @TableField(value = "info")
private String info;
/**
* 操作用户id
*/
@TableField(value = "oper_id")
private Integer operId;
/**
* 操作用户名
*/
@TableField(value = "oper_name")
private String operName;
/**
* 多个用户id
*/
@TableField(exist = false) //说明数据库表中不存在该字段
private String ids;
}
1.5. 创建mapper
mapper继承BaseMapper<表名>
package com.example.my_mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.my_mybatisplus.entity.User;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户层
* BaseMapper<User> :User是实体类
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
1.6. 创建service
(1)service接口继承IService
package com.example.my_mybatisplus.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.my_mybatisplus.entity.User;
public interface UserService extends IService<User> {
}
(2)serviceImpl类继承ServiceImpl接口,实现UserService
/**
* ServiceImpl<UserMapper, User> implements UserService:
* ServiceImpl :mybatis-plus内部,直接调用
* UserMapper : 自定义的Mapper层名字
* User:实体类名
* UserService:自定义的Service接口名;
**/
package com.example.my_mybatisplus.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.mapper.UserMapper;
import com.example.my_mybatisplus.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
1.7. 创建controller
调用UserService中的方法
package com.example.my_mybatisplus.controller;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
// 直接调用service层中的方法
@Autowired
UserService userService;
// 直接调用mapper层中的方法
@Autowired
UserMapper userMapper;
}
1.8 实体类字段默认值设置类
package com.example.my_mybatisplus.utils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 设置新增或修改指定字段的默认值
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 新增:默认数据
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("inTime",new Date(),metaObject);
this.setFieldValByName("operTime",new Date(),metaObject);
this.setFieldValByName("delFlag","0",metaObject);
//可以为其他字段设置默认值
}
/**
* 修改:默认数据
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("operTime",new Date(),metaObject);
//可以在为其他字段设置默认值
}
}
2.mybatis-plus中常用的方法
2.1 增
InsertUserController.java
package com.example.my_mybatisplus.controller;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.mapper.UserMapper;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 新增用户信息
*/
@RestController
@RequestMapping("/insertuser")
public class InsertUserController {
@Autowired
UserService userService;
@Autowired
UserMapper userMapper;
/**
* 新增用户信息(单条记录)
* 方法一(service层):boolean save(T entity);
* 方法二(mapper层):int insert(T entity);
* entity:新增的单个对象值,{}
* @param user
* @return
*/
@PostMapping("/insert")
public R insertUser(@RequestBody User user) {
Boolean save = userService.save(user); //service层的方法
// int insert = userMapper.insert(user); //mapper层的方法
return R.ok(save);
}
/**
* 新增用户信息(批量)
* 方法:boolean saveBatch(Collection<T> entityList);
* entityList:新增的对象数据列表,[]
* 特点:该方法中使用一批次同时插入对象列表中的数据(与数据库交互一次-调用一次数据库)
* @param users
* @return
*/
@PostMapping("/insertBatch")
public R insertBatch(@RequestBody List<User> users){
boolean saveBatch = userService.saveBatch(users); //service层方法
return R.ok(saveBatch);
}
/**
* 新增用户信息(指定批量记录数)
* 方法:boolean saveBatch(Collection<T> entityList, int batchSize);
* entityList:新增的对象数据列表,[]
* batchSize:指定了每次批量插入操作中包含的记录数,设置此值,可以控制每次批量操作的大小,以优化性能和资源使用(减少批量插入与数据库表的交互次数)
* 特点:该方法中batchSize指定每批次插入数据库数据的大小,可以将对象列表中的所有对象根据不同批次大小,分成多批次进行插入(与数据库交互多次-多次调用数据库)
* 例如:对象数据列表中共有7条数据,若batchSize=2,该方法中需要与数据库交互8次(2,2,2,1)
* @param users
* @return
*/
@PostMapping("/insertBatchLimit")
public R insertBatchLimit(@RequestBody List<User> users){
boolean saveBatch = userService.saveBatch(users, 2);
return R.ok(saveBatch);
}
}
2.2 增&改
SaveOrUpdateController.java
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 新增或修改用户信息
*/
@RestController
@RequestMapping("/saveOrUpdateUser")
public class SaveOrUpdate {
@Autowired
UserService userService;
/**
* 新增或修改(单条记录)
* 方法:boolean saveOrUpdate(T entity);
* 判断实体类中的id:
* (1)id为空:新增;
* (2)id非空:修改;
* @param user
* @return
*/
@PostMapping("/saveOrUpdate")
public R saveOrUpdate(@RequestBody User user){
boolean saveOrUpdate = userService.saveOrUpdate(user);
return R.ok(saveOrUpdate);
}
/**
* 新增或修改(单条记录-含条件)
* 方法:boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);(过时方法,不推荐使用)
* updateWrapper:修改的指定字段
* @param user
* @return
*/
@PostMapping("/saveOrUpdateCondition")
public R saveOrUpdateCondition(@RequestBody User user){
// 定义更新指定条件
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.set("sex","0");
boolean saveOrUpdate = userService.saveOrUpdate(user, updateWrapper);
return R.ok(saveOrUpdate);
}
/**
* 新增或修改(批量)
* 方法详细讲解开插入方法
* @param users
* @return
*/
@PostMapping("/saveOrUpdateBatch")
public R saveOrUpdateBatch(@RequestBody List<User> users){
boolean saveOrUpdateBatch = userService.saveOrUpdateBatch(users);
return R.ok(saveOrUpdateBatch);
}
/**
* 新增或修改(批量(指定批量记录数))
* 方法详细讲解开插入方法
* @param users
* @return
*/
@PostMapping("/saveOrUpdateBatchLimit")
public R saveOrUpdateBatchLimit(@RequestBody List<User> users){
boolean saveOrUpdateBatch = userService.saveOrUpdateBatch(users, 2);
return R.ok(saveOrUpdateBatch);
}
}
2.3 删
RemoveController.java
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.mapper.UserMapper;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
* 删除用户(调用方法:service层 + mapper层 + 自定义方法)
*/
@RestController
@RequestMapping("/remove")
public class RemoveController {
@Autowired
UserService userService;
@Autowired
UserMapper userMapper;
/**
* 删除(根据条件删除)
* 方法:boolean remove(Wrapper<T> queryWrapper);
*
* @param user
* @return boolean 直接删除
*/
@PostMapping("/removeByCondition")
public R remove(@RequestBody User user){
// 根据条件删除(根据userName和性别删除(多条件))
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",user.getUserName()).eq("sex",user.getSex());
boolean remove = userService.remove(queryWrapper); //mybatis-plus提供service层的方法
// int delete = userMapper.delete(queryWrapper); //mybatis-plus提供mapper层的方法
// boolean remove = userService.remove(user.getId()); //自定义的删除方法
return R.ok(remove);
}
/**
* 删除(根据id删除)
* 方法:boolean removeById(Serializable id);
* @param user
* @return Boolean 直接删除
*/
@PostMapping("/removeById")
public R removeById(@RequestBody User user){
boolean removeById = userService.removeById(user.getId()); //service层
// int deleteById = userMapper.deleteById(user.getId()); //mapper层
return R.ok(removeById);
}
/**
* 删除(根据map条件)
* 方法:boolean removeByMap(Map<String, Object> columnMap);
* 特点:与boolean remove(Wrapper<T> queryWrapper) 比较
* @param user
* @return Boolean 直接删除
*/
@PostMapping("/removeByMap")
public R removeByMap(@RequestBody User user){
//可以添加多个条件
Map<String,Object> map=new HashMap<>();
map.put("user_name",user.getUserName());
map.put("sex",user.getSex());
boolean removeByMap = userService.removeByMap(map); //service层
// int deleteByMap = userMapper.deleteByMap(map); //mapper层
return R.ok(removeByMap);
}
/**
* 删除(根据id批量)
* 方法:boolean removeByIds(Collection<? extends Serializable> idList);
* 注意:(1)方法的入参是List<Integer>
* (2)将前端传入的字符串组成的id转换成List<Integer>类型
* @param user
* @return Boolean 直接删除
*/
@PostMapping("/removeByIds")
public R removeByIds(@RequestBody User user){
String[] idArray=user.getIds().split(",");
List<Integer> ids = new ArrayList<>();
for(String id:idArray){
ids.add(Integer.valueOf(id));
}
boolean removeByIds = userService.removeByIds(ids); //service层
// int deleteBatchIds = userMapper.deleteBatchIds(ids); //mapper层
return R.ok(removeByIds);
}
}
2.4 改
UpdateController.java
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.mapper.UserMapper;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/update")
public class UpdateController {
@Autowired
UserService userService;
@Autowired
UserMapper userMapper;
/**
* 修改(根据updateWrapper修改)
* 方法:boolean update(Wrapper<T> updateWrapper);
* 特点:使用.eq修改满足条件,.set修改内容
* 注意:(1).eq()中对应的字段值作为条件必传;
* (2).set()中对应的字段值作为修改字段,该值需要传入修改的新值,如果不传值或传空值,则修改对应的字段会修改成空字符串("")或空值(null)
* @param user
* @return
*/
@PostMapping("/updateByUpdateWrapper")
public R updateByUpdateWrapper(@RequestBody User user){
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("user_name",user.getUserName()).set("sex",user.getSex()).set("password",user.getPassword());
boolean update = userService.update(updateWrapper);
return R.ok(update);
}
/**
* 修改(根据updateByWhereWrapper修改)
* 方法:boolean update(T updateEntity, Wrapper<T> whereWrapper);
* 参数:updateEntity 修改的实体类,实体类中是需要修改的内容
* whereWrapper 修改的条件
* 注意:如果根据实体类中的某个字段作为修改条件,则该修改条件不会被修改;
* @param user
* @return
*/
@PostMapping("/updateByWhereWrapper")
public R updateByWhereWrapper(@RequestBody User user){
QueryWrapper<User> whereWrapper = new QueryWrapper<>();
whereWrapper.eq("id",user.getId());
boolean update = userService.update(user, whereWrapper); //service层
// int update = userMapper.update(user, whereWrapper); //mapper层
return R.ok(update);
}
/**
* 修改(根据id修改)
* 方法:boolean updateById(T entity);
* 参数:entity 修改对象(其中id值必传)
* @param user
* @return
*/
@PostMapping("/updateById")
public R updateById(@RequestBody User user){
boolean updateById = userService.updateById(user); //service层
// int updateById = userMapper.updateById(user); //mapper层
return R.ok(updateById);
}
/**
* 修改(根据id批量)
* 方法:boolean updateBatchById(Collection<T> entityList);
* 参数:entityList 对象列表,[]
* 注意:(1)参数列表中的每个对象的id都要传入;
* (2)如果传入的多个id,在数据库表中有存在有不存在,则会修改存在的对象,不存在的对象不会做出修改
* @param users
* @return
*/
@PostMapping("/updateBatchById")
public R updateBatchById(@RequestBody List<User> users){
boolean updateBatchById = userService.updateBatchById(users);
return R.ok(updateBatchById);
}
/**
* 修改(根据id批量修改,指定批量记录数)
* 方法:boolean updateBatchById(Collection<T> entityList, int batchSize);
* @param users
* @return
*/
@PostMapping("/updateBatchByIdLimit")
public R updateBatchByIdLimit(@RequestBody List<User> users){
boolean updateBatchById = userService.updateBatchById(users, 2);
return R.ok(updateBatchById);
}
}
2.5 查
2.5.1 get
GetController
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/get")
public class GetController {
@Autowired
UserService userService;
/**
* 查询(根据id查询)
* 方法:T getById(Serializable id);
* 注意:若实体类中存在数据库表中没有的字段,需要在实体类中非数据库表中字段的上面加上注解@TableField(exist = false)
*
* @param user
* @return user
*/
@PostMapping("/getById")
public R getById(@RequestBody User user) {
User byId = userService.getById(user.getId());
return R.ok(byId);
}
/**
* 查询(根据queryWrapper,查询一条记录,结果集,如果是多个会抛出异常,随机取一条加上限制条件Wrapper.last("LIMIT 1"))
* 方法:T getOne(Wrapper<T> queryWrapper);
* 参数:queryWrapper 查询条件
* @param user
* @return
*/
@PostMapping("/getOneByQueryWrapper")
public R getOneByQueryWrapper(@RequestBody User user) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("sex", user.getSex()).last("LIMIT 1");
User one = userService.getOne(queryWrapper);
return R.ok(one);
}
/**
* 查询(查询一条记录,不抛出异常)
* 方法:T getOne(Wrapper<T> queryWrapper, boolean throwEx);
* 参数:(1)queryWrapper:查询条件
* (2)throwEx:抛异常限制,false(不抛异常)
* @param user
* @return 返回一条数据 第一条
*/
@PostMapping("/getOne")
public R getOne(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("sex", user.getSex());
User one = userService.getOne(queryWrapper,false);
return R.ok(one);
}
/**
* 查询(根据Wrapper条件)
* 方法:Map<String, Object> getMap(Wrapper<T> queryWrapper);
* @param user
* @return Map类型(一条数据)
*/
@PostMapping("/getMap")
public R getMap(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",user.getUserName());
Map<String, Object> map = userService.getMap(queryWrapper);
return R.ok(map);
}
/**
* 方法:<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);(待学习)
* 参数:(1)queryWrapper 查询条件
* (2)mapper
* 作用:queryWrapper设置查询条件,并将结果转换为Strign类型
* @param user
* @return String 一条记录
*/
@PostMapping("/getObject")
public R getObject(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",user.getUserName());
// Map<String, Object> map = userService.getMap(queryWrapper);
String userName = userService.getObj(queryWrapper, obj -> {
System.out.println(obj); //此时obj查询的结果是对象记录中的id
if(obj instanceof User){
return ((User) obj).getUserName();
}else{
return null;
}
});
return R.ok(userName);
}
}
2.5.2 list
ListController.java
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.mapper.UserMapper;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/list")
public class ListController {
@Autowired
UserService userService;
@Autowired
UserMapper userMapper;
/**
* 查询(所有)
* 方法:List<T> list();
* @param user
* @return
*/
@PostMapping("/list")
public R list(@RequestBody(required = false) User user){
List<User> users = userService.list();
return R.ok(users);
}
/**
* 查询(根据条件查询列表)
* 方法:List<T> list(Wrapper<T> queryWrapper);
* @param user
* @return
*/
@PostMapping("/listByWrapper")
public R listByWrapper(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",user.getUserName());
List<User> list = userService.list(queryWrapper);
return R.ok(list);
}
/**
* 查询(根据id批量查询)
* 方法:Collection<T> listByIds(Collection<? extends Serializable> idList);
* @param user
* @return
*/
@PostMapping("/listByIds")
public R listByIds(@RequestBody User user){
String[] idsArray=user.getIds().split(",");
List<Integer> ids=new ArrayList<>();
for(String id:idsArray){
ids.add(Integer.valueOf(id));
}
List<User> users = userService.listByIds(ids);
return R.ok(users);
}
/**
* 查询(根据条件查询(map))
* 方法:Collection<T> listByMap(Map<String, Object> columnMap);
* @param user
* @return
*/
@PostMapping("/listByMap")
public R listByMap(@RequestBody User user){
Map<String,Object> map=new HashMap<>();
map.put("user_name",user.getUserName());
List<User> users = userService.listByMap(map);
return R.ok(users);
}
/**
* 查询所有,将结果映射为Map
* 方法:List<Map<String, Object>> listMaps();
* @param user
* @return 将所有查询结果返回为list列表
*/
@PostMapping("/listMaps")
public R listMaps(@RequestBody(required = false) User user){
List<Map<String, Object>> maps = userService.listMaps();
return R.ok(maps);
}
/**
* 查询(条件查询结果,将结果映射为map列表)
* @param user
* @return list列表
*/
@PostMapping("/listMapsByWrapper")
public R listMapsByWrapper(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",user.getUserName());
List<Map<String, Object>> maps = userService.listMaps(queryWrapper);
return R.ok(maps);
}
/**
* 查询(列表)
* 方法:List<Object> listObjs();
* @param user
* @return 返回所有记录的id
*/
@PostMapping("/listObjs")
public R listObjs(@RequestBody(required = false) User user){
List<User> users = userService.listObjs();
return R.ok(users);
}
/**
* 根据条件查询(列表)
* 方法:List<Object> listObjs(Wrapper<T> queryWrapper);
* @param user
* @return 返回结果对应的id
*/
@PostMapping("/listObjsByWrapper")
public R listObjsByWrapper(@RequestBody(required = false) User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",user.getAge());
List<User> list = userService.listObjs(queryWrapper);
return R.ok(list);
}
/**
* 查询(根据条件查询)
* 方法:<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
* @param user
* @return 返回值为String类型
*/
@PostMapping("/listObjsByWrapperString")
public R listObjsByWrapperString(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",user.getAge());
List<String> list = userService.listObjs(queryWrapper, obj -> {
System.out.println(obj);
if(obj instanceof User){
// if(obj !=null){
return ((User) obj).getUserName();
}else{
return null;
}
});
return R.ok(list);
}
}
2.5.3 page
mybatis分页和mybatis-plus分页使用的区别:
mybatis分页:只需要加上依赖;
mybatis-plus分页:只需要加个配置类(MybatisPlusConfig.java);
MybatisPlusConfig.java配置类
package com.example.my_mybatisplus.utils;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 分页配置类
*/
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setOptimizeJoin(true);
paginationInnerInterceptor.setDbType(DbType.MYSQL);
paginationInnerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor = new OptimisticLockerInnerInterceptor();
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);
return interceptor;
}
}
PageController.java
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.mapper.UserMapper;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/page")
public class PageController {
@Autowired
UserService userService;
@Autowired
UserMapper userMapper;
/**
* 无条件分页查询
* 方法:IPage<T> page(IPage<T> page);
* @param user
* @return records(数据列表)、size(页面大小)、pages(总页数)、total(总条数)、current(当前页)
*/
@PostMapping("/page")
public R page(@RequestBody User user){
IPage<User> page = new Page<>(user.getCurrentPage(), user.getPageSize());
IPage<User> userPage = userService.page(page); //调用page方法
return R.ok(userPage);
}
/**
* 条件分页查询
* 方法:IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
* @param user
* @return records(数据列表)、size(页面大小)、pages(总页数)、total(总条数)、current(当前页)
*/
@PostMapping("/pageByWrapper")
public R pageByWrapper(@RequestBody User user){
IPage<User> page=new Page<>(user.getCurrentPage(),user.getPageSize());
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",user.getUserName());
IPage<User> pages = userService.page(page,queryWrapper);
return R.ok(pages);
}
/**
* 无条件分页查询(将结果映射为map)(待研究)
* 方法:IPage<Map<String, Object>> pageMaps(IPage<T> page);
* @param user
* @return records(数据列表)、size(页面大小)、pages(总页数)、total(总条数)、current(当前页)
*/
@PostMapping("/pageMaps")
public R pageMaps(@RequestBody User user){
IPage<User> page=new Page<>(user.getCurrentPage(),user.getPageSize());
IPage<Map<String,Object>> userPageMaps = userService.pageMaps(page);
return R.ok(userPageMaps);
}
/**
* 条件分页查询(将结果映射为map)(待研究)
* 方法:IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);
* @param user
* @return
*/
@PostMapping("/pageMapsByWrapper")
public R pageMapsByWrapper(@RequestBody User user){
IPage<User> page=new Page<>(user.getCurrentPage(),user.getPageSize());
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",user.getUserName());
IPage<Map<String,Object>> pageMaps = userService.pageMaps(page, queryWrapper);
return R.ok(pageMaps);
}
}
2.5.4 count
CountController.java
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.mapper.UserMapper;
import com.example.my_mybatisplus.service.UserService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/count")
public class CountController {
@Autowired
UserService userService;
@Autowired
UserMapper userMapper;
/**
* 查询总记录数
* 方法:int count();
* @param user
* @return 返回值类型 3.4.3.2前是int类型,之后是long类型
*/
@PostMapping("/count")
public R count(@RequestBody(required = false) User user){
long count = userService.count();
return R.ok(count);
}
/**
* 查询总记录数(有条件)
* 方法:long count(Wrapper<T> queryWrapper);
* @param user
* @return 返回值类型 3.4.3.2前是int类型,之后是long类型
*/
@PostMapping("/countByWrapper")
public R countByWrapper(@RequestBody(required = false) User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",user.getUserName());
long count = userService.count(queryWrapper);
return R.ok(count);
}
}
2.5.5 直接调用mappr中的查询方法
MapperSelectController
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.my_mybatisplus.entity.User;
import com.example.my_mybatisplus.mapper.UserMapper;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/select")
public class MapperSelectController {
@Autowired
UserMapper userMapper;
/**
* 根据id查询
* 方法:T selectById(Serializable id);
*
* @param user
* @return
*/
@PostMapping("/selectById")
public R selectById(@RequestBody User user) {
User user1 = userMapper.selectById(user.getId());
return R.ok(user1);
}
/**
* 根据实体类中条件查询(查询一条)
* 注意:由于该方法返回结果是对象,所以在查询条件中加入条件.last("limit 1")
* 方法:T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
*
* @param user
* @return
*/
@PostMapping("/selectOne")
public R selectOne(@RequestBody User user) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age", user.getAge()).last("limit 1");
User user1 = userMapper.selectOne(queryWrapper);
return R.ok(user1);
}
/**
* 根据id批量查询
* 方法:List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
*
* @param user
* @return
*/
@PostMapping("/selectBatchIds")
public R selectBatchIds(@RequestBody User user) {
String[] idsArray = user.getIds().split(",");
List<Integer> ids = new ArrayList<>();
for (String id : idsArray) {
ids.add(Integer.valueOf(id));
}
List<User> users = userMapper.selectBatchIds(ids);
return R.ok(users);
}
/**
* 根据条件查询数据记录
* 方法:List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
* @param user
* @return 返回值list类型
*/
@PostMapping("/selectList")
public R selectList(@RequestBody User user) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",user.getAge());
List<User> users = userMapper.selectList(queryWrapper);
return R.ok(users);
}
/**
* 根据map条件查询
* 方法:List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
* 参数:map类型
* @param user
* @return
*/
@PostMapping("/selectByMap")
public R selectByMap(@RequestBody User user){
Map<String, Object> map = new HashMap<>();
map.put("age",user.getAge());
List<User> users = userMapper.selectByMap(map);
return R.ok(users);
}
/**
* 根据条件查询
* 方法:List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
* @param user
* @return 返回值类型为列表
*/
@PostMapping("/selectMaps")
public R selectMaps(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",user.getAge());
List<Map<String,Object>> users = userMapper.selectMaps(queryWrapper);
return R.ok(users);
}
/**
* 根据条件查询全部记录,只返回第一个字段的值
* 方法:List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
* @param user
* @return
*/
@PostMapping("/selectObjs")
public R selectObjs(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",user.getAge());
List<User> objects = userMapper.selectObjs(queryWrapper);
return R.ok(objects);
}
/**
* 根据条件分页查询
* 方法:IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
* @param user
* @return
*/
@PostMapping("/selectPage")
public R selectPage(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",user.getAge());
IPage<User> page=new Page<>(user.getCurrentPage(),user.getPageSize());
IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
return R.ok(userIPage);
}
/**
* 条件分页查询(记录)(待研究)
* 方法:IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
* @param user
* @return
*/
@PostMapping("/selectMapsPage")
public R selectMapsPage(@RequestBody User user){
IPage<User> page=new Page<>(user.getCurrentPage(),user.getPageSize());
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",user.getAge());
IPage<User> p = userMapper.selectMapsPage(page, queryWrapper);
return R.ok(p);
}
/**
* 条件查询总记录数
* 方法:Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
* @param user
* @return
*/
@PostMapping("/selectCount")
public R selectCount(@RequestBody User user){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",user.getAge());
Long aLong = userMapper.selectCount(queryWrapper);
return R.ok(aLong);
}
}
3. 自定义方法
1.若自定义方法和mybatis-plus中重名,则自定义方法优先被执行;
3.1 yml文件
application.yml
#mabatis-plus的配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印sql日志
map-underscore-to-camel-case: true # 是否开启驼峰命名转换
mapper-locations: classpath:/mappers/**/*.xml #用于指定XXXmapper.xml的路径
type-aliases-package: com.example.my_mybatisplus.entity #用于指定Mybatis-plus自动扫描并注册别名(alias)的实体类所在的包路径(默认使用实体类的简单名称(首字母小写)作为别名)
3.2 UserMapper.xml文件
UserMapper.xml1
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.my_mybatisplus.mapper.UserMapper">
<update id="remove">
update s_user
set del_flag='3'
where id = #{id}
</update>
</mapper>
3.3 Mapper文件
同mybatis
3.4 Service文件
同mybatis
3.5 Controller文件
同mybatis
4. Mapper层选装件
在MyBatis-Plus中,选装件(或称为插件)的使用是为了增强MyBatis-Plus的功能,满足开发者在复杂业务场景下的需求。
(有待学习)
5.Chain
Chain 是 Mybatis-Plus 提供的一种链式编程风格,它允许开发者以更加简洁和直观的方式编写数据库操作代码。Chain 分为 query 和 update 两大类,分别用于查询和更新操作。每类又分为普通链式和 lambda 链式两种风格,其中 lambda 链式提供了类型安全的查询条件构造,但不支持 Kotlin。
QueryChainWrapper和UpdateChainWrapper 使用 QueryWrapper和UpdateWrapper 代替
6. ActiveRecord
ActiveRecord 模式是一种设计模式,它允许实体类直接与数据库进行交互,实体类既是领域模型又是数据访问对象。在 Mybatis-Plus 中,实体类只需继承 Model 类即可获得强大的 CRUD 操作能力
7.SimpleQuery
SimpleQuery 是 Mybatis-Plus 提供的一个工具类,它对 selectList 查询后的结果进行了封装,使其可以通过 Stream 流的方式进行处理,从而简化了 API 的调用。
SimpleQuery 的一个特点是它的 peeks 参数,这是一个可变参数,类型为 Consumer…,意味着你可以连续添加多个操作,这些操作会在查询结果被处理时依次执行。
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery;
import com.example.my_mybatisplus.entity.Profession;
import com.example.my_mybatisplus.service.ProfessionService;
import com.example.my_mybatisplus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* Simple Query
* 直接调用,注意:使用的实体类中对应的mapper层要继承BaseMapper
*/
@RestController
@RequestMapping("/simpleQuery")
public class SimpleQueryController {
@Autowired
ProfessionService professionService;
/**
* 使用 keyMap方法查询并封装结果
* 方法:Map<A, E> keyMap(LambdaQueryWrapper<E> wrapper, SFunction<E, A> sFunction, Consumer<E>... peeks);
* 作用:查询表内记录,封装返回为Map<属性,实体>,方法适用于需要根据实体的某个属性快速查找实体的场景。
* 参数:(1)SFunction:可以指定任何实体属性作为Map的键,是查询结果的访问更加直观和高效;
* (2)peeks:允许在处理查询结果时,执行额外的副作用操作,这些结果不会影响最终的Map结果;
* (3)isParallel:当处理大量数据时,可以考虑将该参数设置为true以启动并行流,从而提高查询效率;
*
* @param profession
* @return
*/
@PostMapping("/queryByKeyMap")
public R queryByKeyMap(@RequestBody(required = false) Profession profession) {
LambdaQueryWrapper<Profession> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Profession::getDelFlag, "0"); //查询del_flag='0' 的职业
Map<String, Profession> professionMap = SimpleQuery.keyMap(
queryWrapper, //查询条件构造器
Profession::getProfessionName, //使用职业名为键,
profession1 -> System.out.println("processing:" + profession1.getProfessionName()) //打印处理的用户名
);
return R.ok(professionMap);
}
/**
* 使用map方法查询表内记录,并封装返回为Map<属性,属性>结果
* 方法:Map<A, P> map(LambdaQueryWrapper<E> wrapper, SFunction<E, A> keyFunc, SFunction<E, P> valueFunc, Consumer<E>... peeks);
* 作用:map方法适用于需要根据实体的某个属性快速查找另一个属性的场景;
* 参数:(1)keyFunc:可以指定任何实体属性作为Map的键和值,这使得查询结果的访问更加直观和高效;
* (2)valueFunc:同上;
* (3)peeks:允许在处理查询结果时,执行额外的副作用操作,这些操作不会影响最终的Map结果
*
* @param profession
* @return
*/
@PostMapping("/queryByMap")
public R queryByMap(@RequestBody(required = false) Profession profession) {
LambdaQueryWrapper<Profession> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Profession::getDelFlag, "0");
Map<String, String> professionMap = SimpleQuery.map(
queryWrapper, //查询条件
Profession::getProfessionName, //使用职业名作为键
Profession::getInfo, //使用职业描述作为值
profession1 -> System.out.println("Processing:" + profession1.getProfessionName()) //打印
);
return R.ok(professionMap);
}
/**
* 使用group方法查询表内记录,并封装返回为Map<属性,List<实体>>
* 方法:Map<K, List<T>> group(LambdaQueryWrapper<T> wrapper, SFunction<T, K> sFunction, Consumer<T>... peeks);
* 作用:适用于需要根据实体的某个属性对查询结果进行分组的场景;
* 参数:(1)sFunction:可指定任何实体属性作为分组的依据,这使查询结果的组织更加灵活;
* (2)downstream:允许使用Collector对分组后的集合进行进一步的处理,如计数、求和、平均值等
* (3)peeks:允许在处理查询结果时执行额外的副作用操作,这些操作不会影响选哪个最终的Map结果
*
* @param profession
* @return
*/
@PostMapping("/queryByGroup")
public R queryByGroup(@RequestBody(required = false) Profession profession) {
LambdaQueryWrapper<Profession> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Profession::getDelFlag, "0");
Map<String, List<Profession>> professionGroup = SimpleQuery.group(
queryWrapper, //查询条件构造器
Profession::getProfessionName, //使用del_flag作为分组键
profession1 -> System.out.println("Processing:" + profession1.getProfessionName()) //打印
);
// for(Map.Entry<String,List<Profession>> entry:professionGroup.entrySet()){
// System.out.println("delFlag:"+entry.getKey());
// for(Profession profession1: entry.getValue()){
// System.out.println("- profession:"+profession1);
// }
// }
return R.ok(professionGroup);
}
/**
* 使用list方法查询表内记录,并封装返回为List<属性>
* 方法:List<A> list(LambdaQueryWrapper<E> wrapper, SFunction<E, A> sFunction, Consumer<E>... peeks);
* 参数:(1)sFunction:可指定任何实体属性作为list的依据,这使查询结果的组织更加灵活;
* (2)peeks:允许在处理查询结果时执行额外的副作用操作,这些操作不会影响选哪个最终的Map结果
* @param profession
* @return
*/
@PostMapping("/queryByList")
public R queryByList(@RequestBody(required = false) Profession profession) {
LambdaQueryWrapper<Profession> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Profession::getDelFlag, "0");
List<String> names = SimpleQuery.list(
queryWrapper, //查询条件
Profession::getProfessionName, //提取职业名作为列表元素
profession1 -> System.out.println("processing:" + profession1.getProfessionName()) //打印
);
return R.ok(names);
}
}
8.Db Kit
Db Kit 提供了一系列静态方法,可以直接调用进行数据库操作,无需通过 Service 层,简化了代码结构。
在使用 Db Kit 时,确保传入的参数正确,特别是当使用 Wrapper 时,需要指定实体类或实体对象。
对于批量操作,如批量插入或更新,建议使用 Db Kit 提供的批量方法,以提高效率。
避免在循环中频繁调用 Db Kit 的方法,这可能会导致性能问题。
DbKitController.java
package com.example.my_mybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.my_mybatisplus.entity.Profession;
import com.example.my_mybatisplus.utils.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
/**
* Db Kit
* 直接调用,注意:使用的实体类中对应的mapper层要继承BaseMapper
*/
@RestController
@RequestMapping("/dbKit")
public class DbKitController {
/**
* 根据id查询单个实体
*
* @param profession
* @return
*/
@PostMapping("/getById")
public R getById(@RequestBody(required = false) Profession profession) {
Profession profession1 = Db.getById(profession.getId(), Profession.class);
return R.ok(profession1);
}
/**
* 根据id查询多个实体
*
* @param profession
* @return
*/
@PostMapping("/userList")
public R userList(@RequestBody(required = false) Profession profession) {
List<Profession> professionList = Db.listByIds(Arrays.asList(1, 2, 3), Profession.class);
return R.ok(professionList);
}
/**
* 根据条件构造器查询
*
* @param profession
* @return
*/
@PostMapping("/queryWrapper")
public R queryWrapper(@RequestBody(required = false) Profession profession) {
LambdaQueryWrapper<Profession> queryWrapper = Wrappers.lambdaQuery(Profession.class).eq(Profession::getDelFlag, profession.getDelFlag());
List<Profession> professionList = Db.list(queryWrapper);
return R.ok(professionList);
}
/**
* 插入新实体
* @param profession
* @return
*/
@PostMapping("/insert")
public R insert(@RequestBody Profession profession) {
Boolean isInserted = Db.save(profession);
return R.ok(isInserted);
}
/**
* 根据id修改
*
* @param profession
* @return
*/
@PostMapping("/updateById")
public R update(@RequestBody Profession profession) {
boolean isUpdated = Db.updateById(profession);
return R.ok(isUpdated);
}
/**
* 根据条件修改
*
* @param profession
* @return
*/
@PostMapping("/updateByWrapper")
public R updateByWrapper(@RequestBody Profession profession) {
LambdaUpdateWrapper<Profession> updateWrapper = Wrappers.lambdaUpdate(Profession.class)
.set(Profession::getDelFlag, profession.getDelFlag())
.eq(Profession::getProfessionName, profession.getProfessionName());
boolean isUpdateByWrapper = Db.update(null, updateWrapper);
return R.ok(isUpdateByWrapper);
}
/**
* 根据id删除
*
* @param profession
* @return
*/
@PostMapping("/deleteById")
public R deleteById(@RequestBody Profession profession) {
Boolean isDeleted = Db.removeById(profession.getId());
return R.ok(isDeleted);
}
/**
* 批量插入
* @param professions
* @return
*/
@PostMapping("/batchsInsert")
public R batchsInsert(@RequestBody List<Profession> professions) {
Boolean isBatchInserted=Db.saveBatch(professions);
return R.ok(isBatchInserted);
}
/**
* 批量修改
* @param professions
* @return
*/
@PostMapping("/batchsUpdate")
public R batchsUpdate(@RequestBody List<Profession> professions){
Boolean isBatchUpdated=Db.updateBatchById(professions);
return R.ok(isBatchUpdated);
}
}
mybatis-plus官网:https://baomidou.com/guides/data-interface/#save