1、分页插件的配置
@Configuration
//扫描mapper接口所在的包
@MapperScan("com.peng.mybatisplus.mapper")
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
1.2、自定义分页功能
1.2.1实体类
@Data
//设置实体类所对应的表
//@TableName("t_user")
public class User {
//将属性所对应的字段指定为主键
//@TableId注解的value属性用于指定主键的字段
//@TableId(value = "uid", type = IdType.AUTO)
@TableId("uid")
private Long id;
@TableField("user_name")
private String name;
private Integer age;
private String email;
@TableLogic
private Integer isDeleted;
}
1.2.2在mapper接口中
/**
* 通过年龄查询用户信息并分页
* @param page MyBatis-Plus所提供的分页对象,必须位于第一个参数的位置
* @param age
* @return
*/
Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);
1.2.3在yml文件中配置类型别名
# 配置类型别名所对应的包
type-aliases-package: com.peng.mybatisplus.pojo
1.2.4在映射文件xml中
<!--Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);-->
<select id="selectPageVo" resultType="User">
select uid,user_name,age,email from t_user where age > #{age}
</select>
1.2.5在测试类中
@SpringBootTest
public class MyBatisPlusPluginsTest {
@Autowired
private UserMapper userMapper;
@Test
public void testPageVo(){
Page<User> page = new Page<>(1,3);
userMapper.selectPageVo(page,20);
System.out.println(page);
}
}
2、乐观锁插件
2.1实体类
@Data
public class Product {
private Long id;
private String name;
private Integer price;
@Version //标识乐观锁版本号字段
private Integer version;
}
2.2在mapper接口中
@Repository
public interface ProductMapper extends BaseMapper<Product> {
}
2.3测试类
@SpringBootTest
public class MyBatisPlusPluginsTest {
@Autowired
private ProductMapper productMapper;
@Test
public void testProduct01(){
// 小李查询的商品价格
Product productLi = productMapper.selectById(1);
System.out.println("小李查询的商品价格: "+productLi.getPrice());
// 小王查询的商品价格
Product productWang = productMapper.selectById(1);
System.out.println("小王查询的商品价格: "+productWang.getPrice());
// 小李将商品价格+50
productLi.setPrice(productLi.getPrice()+50);
productMapper.updateById(productLi);
// 小王将商品价格-30
productWang.setPrice(productWang.getPrice()-30);
int result = productMapper.updateById(productWang);
if (result == 0){
Product productNew = productMapper.selectById(1);
productNew.setPrice(productNew.getPrice()-30);
productMapper.updateById(productNew);
}
// 老板查询商品价格
Product productLaoBan = productMapper.selectById(1);
System.out.println("老板查询的商品价格: "+productLaoBan.getPrice());
}
}