MybatisPlus
MybatisPlus入门案例
官方网站:https://baomidou.com/
只做增强,引入不会对现有工程产生影响
操作步骤
-
引入依赖
依赖中集成了Mybatis和mybatisPlus中的所有功能。
<!--MybatisPlus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.1</version> </dependency>
-
定义Mapper接口并继承BaseMapper
userMapper
public interface UserMapper extends BaseMapper<User> { }
testMapper
userMapper.insert(user) //新增 userMapper.selectById(5L) //查询 userMapper.updateById(user) //更改 userMapper.deleteById(user) //删除
常见注解
- @TableName->用来指定表名
- @TableId->用来指定表中的主键Id
- @TableField->用来指定表中的普通字段信息
常见配置
mybatis-plus:
type-aliases-package: com.itheima.mp.domain.po # 别名扫描包
mapper-locations: "classpath*:/mapper/**/*.xml" # Mapper.xml文件地址,默认值 configuration: map-underscore-to-camel-case: true # 是否开启下划线和驼峰的映射
cache-enabled: false # 是否开启二级缓存
global-config:
db-config: id-type: assign_id # id为雪花算法生成
update-strategy: not_null # 更新策略:只更新非空字段
id-type: auto //主键自增
具体操作文档:使用配置 | MyBatis-Plus(baomidou.com)
核心功能
条件构造器条件构造器 | MyBatis-Plus (baomidou.com)
基于QueryWrapper条件
- 查询
@Test
void testQueryList() {
//构建查询条件
QueryWrapper<User> wrapper = new QueryWrapper<User>()
.select("id","username","info","balance")
.like("username","o")
.ge("balance",1000);
//查询
List<User> mapper=userMapper.selectList(wrapper);
mapper.forEach(System.out::println);
}
- 更改
@Test
void testQueryUpdate(){
//要更新的数据
User user=new User();
user.setBalance(5000);
//
QueryWrapper<User> wrapper = new QueryWrapper<User>()
.eq("username","Jack");
//更新
userMapper.update(user,wrapper);
}
基于updateWrapper更改
@Test
void testUpdateWrapper(){
List<Long> ids=List.of(1L,2L,4L);
//更新条件
UpdateWrapper<User> wrapper=new UpdateWrapper<User>()
.setSql("balance=balance-200")
.in("id",ids);
userMapper.update(null,wrapper);
}
基于lambdaQueryWrapper
自定义SQL
步骤
- 基于Wrapper构建where条件
List<Long> ids = List.of(1L, 2L, 4L);
int amount = 200;
// 1.构建条件
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().in(User::getId, ids);
// 2.自定义SQL方法调用
userMapper.updateBalanceByIds(wrapper, amount);
- 在mapper方法参数中用Param注解声明wrapper变量名称,必须是ew
void updateBalanceByIds(@Param("ew") LambdaQueryWrapper<User> wrapper, @Param("amount") int amount);
- 自定义SQL,并使用Wrapper条件
xml文件
<update id="updateBalanceByIds">
UPDATE tb_user SET balance = balance - #{amount} ${ew.customSqlSegment}
</update>
Iservice接口基本用法
自定义Service接口继承Service接口
public interface UserService extends IService<User> {
}
自定义实现类并继承ServiceImpl类
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
}
测试
void testPrint(){
List<User> users=userService.listByIds(List.of(1L,2L,4L));
users.forEach(System.out::println);
}
Iservice开发基本业务
引入依赖
<!--swagger-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 用户新增
@ApiOperation("用户新增")
@PostMapping
public void saveUser(@RequestBody UserFormDTO userDto) {
log.info("用户新增:{}",userDto);
User user = BeanUtil.copyProperties(userDto, User.class);
userService.save(user);
}
- 用户删除
@ApiOperation("用户删除")
@DeleteMapping("{id}")
public void deleteUser(@PathVariable("id") Long id) {
log.info("用户删除id:{}",id);
userService.removeById(id);
}
- 用户查询–当前获取类型为po类型,需返回为Vo类型
@ApiOperation("用户查询")
@DeleteMapping("{id}")
public UserVO selectUser(@PathVariable("id") Long id) {
log.info("用户查询id:{}",id);
User byId = userService.getById(id);
UserVO userVO = BeanUtil.copyProperties(byId, UserVO.class);
return userVO;
}
Iservice的lambda
查询
controller
@ApiOperation("根据复杂条件查询")
@GetMapping("list")
public List<UserVO> queryUser(UserQuery userQuery) {
//查询用户
List<User> user=userService.queryList
(userQuery.getName(),userQuery.getStatus(),userQuery.getMinBalance(),userQuery.getMaxBalance());
return BeanUtil.copyToList(user, UserVO.class);
}
serviceImpl
public List<User> queryList(String name, Integer status, Integer minBalance, Integer maxBalance) {
List<User> users = lambdaQuery()
.like(name != null, User::getUsername, name)
.eq(status != null, User::getStatus, status)
.ge(minBalance != null, User::getBalance, minBalance)
.le(maxBalance != null, User::getBalance, maxBalance)
.list();
return users;
}
……page()–分页查询
……one()–查询单个
……list()–查询多个
更新
public void deductaction(Long id, Integer money) {
……
int remain=user.getBalance()-money;
lambdaUpdate()
.set(User::getBalance,remain)
.set(remain==0,User::getStatus,2) //判断当前用户余额,如果为0;则将状态改位冻结
.eq(User::getId,id)
.eq(User::getBalance,user.getBalance()) //添加乐观锁
.update();
}
&rewriteBatchedStatements=true
在ClientPreparedStatement的executeBatchInternal中,有判断rewriteBatchedStatements值是否为true并重写SQL的功能,将多条SQL语句转换为一条语句,将执行效率大大提升。
标签:MybatisPlus,List,wrapper,public,user,id,User From: https://blog.csdn.net/2301_79927388/article/details/144119325