title
- 查询 单值,多个主键,条件
- 分页查询
- 物理删除,逻辑删除
mybatis-plus 新增,修改
查询 单值,多个主键,条件
@Testvoid queryOne() {// 查询单个userUser user = userMapper.selectById(1);System.out.println(user);}@Testvoid queryBatchUser() {// 根据id查询多个userList<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));users.forEach(System.out::println);}@Testvoid queryByMap() {// 多条件查询Map<String, Object> conditionParamMap = new HashMap<>();conditionParamMap.put("name", "Jack");conditionParamMap.put("id", "2");List<User> users = userMapper.selectByMap(conditionParamMap);users.forEach(System.out::println);}
分页查询
package cn.bitqian.config;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;/*** mybatis plus配置类* @author echo lovely* @date 2020/11/15 09:48*/@EnableTransactionManagement // 开启事务
@MapperScan("cn.bitqian.mapper")
@Configuration
public class MyBatisPlusConfig {// mybatis插件注册@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {// 分页查询PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();// 添加分页查询到插件中mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);return mybatisPlusInterceptor;}}
分页测试
@Testvoid queryByPaging() {int pageNum = 1;int pageSize = 5;Page<User> page = new Page<>(pageNum, pageSize);Page<User> userPage = userMapper.selectPage(page, null);// 遍历 useruserPage.getRecords().forEach(System.out::println);}
物理删除,逻辑删除
物理删除:是真的把数据库从数据删除。
多条件删除
@Testvoid deleteById() {// ctrl shift zuserMapper.deleteById(1327447426226786310l);}@Testvoid deleteBatchByIds() {userMapper.deleteBatchIds(Arrays.asList(1327447426226786306l,1327447426226786307l));}@Testvoid deleteBatchByCondition() {Map<String, Object> conditionParamMap = new HashMap<>();// 删除name为abc的conditionParamMap.put("name", "abc");userMapper.deleteByMap(conditionParamMap);}
逻辑删除:有一个专门对应的列,表示删除状态的列。删除执行的是修改。
当查询的时候,查询没被改的状态。修改与查询同理。
为user表添加字段
// 逻辑删除字段@TableLogicprivate int deleted;
配置yaml,做逻辑删除会修改的值
# log4j std out
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# global 逻辑删除配置global-config:db-config:logic-delete-field: deleted # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置@TableLogic注解)logic-delete-value: 1 # 逻辑已删除值(默认为 1)logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
测试删除
// 逻辑删除 实际上是修改@Testvoid deleteByLogic() {// 被逻辑删除后的值不会被查询,修改到// SELECT id,name,age,email,version,deleted,gmt_create,gmt_modify FROM user WHERE id=? AND deleted=0userMapper.deleteById(1l);}
delete ⇒ update