SpringBoot中使用MybatisPlus
导入MybatisPlus依赖
注意:引入 MyBatis-Plus 之后请不要再次引入 MyBatis,以避免因版本差异导致的问题。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
1.书写mapper接口继承BaseMapper
public interface UserMapper extends BaseMapper<User>
说明:其中泛型的具体类型为需要操作的表对应的实体类
MybatisPlus提供简单的CRUD无需书写XML文件,MybatisPlus也提供条件构造抽象类Wrapper,可不书写XML完成条件查询
建议:除了简单的CRUD都用XML写SQL语句,因为Wrapper拼出来的条件查询代码又臭又长
2.书写Service接口继承IService接口,泛型如上
public interface UserService extends IService<User>
3.书写service实现类继承MybatisPlus的ServiceImpl<M extends BaseMapper,T>并实现自定义的service接口
public class UserSetServiceImpl extends ServiceImpl<UserMapper, User> implements UserService
条件查询示例:serviceImpl方法实现
//注入Mapper接口
@Resource
private UsertMapper userMapper;
/**
* 分页查询,条件:通过用户名和用户编号查,若无条件则查所有
* @param queryVo User对象,有用户名真实姓名等属性
* @param current 当前页数
* @param size 当前页显示条数
* @return MybatisPlus简单分页模型
*/
@Override
public Page<User> findPageListByConditon(UserQueryVo queryVo, Integer current, Integer size) {
//Mybatis plus分页
Page<User> pages = new Page<>(current,size);
//查询
Page<User> returnList = UserMapper.
findPageListByConditon(pages,queryVo);
return returnList;
}
Controller方法实现
//具体参数传递方式根据需求调整
public Page<User> findPageListByConditon(@PathVariable Integer current,
@PathVariable Integer limit,
@RequestBody UserQueryVo queryVo) {
Page<User> returnList = UserService.findPageListByConditon(queryVo, current, limit);
return returnList;
XML文件
<mapper namespace="UserMapper">
<select id ="findPageListByConditon" resultType="User">
select * from User
<where>
<if test="queryVo.username != null and queryVo.username != ''">
and hosname = #{queryVo.hosname,jdbcType=VARCHAR}
</if>
<if test="queryVo.usercode != null and queryVo.usercode != ''">
and hoscode = #{queryVo.hoscode,jdbcType=VARCHAR}
</if>
</where>
</select>
</mapper>
若运行时控制台报OgnlException,参考
https://blog.csdn.net/southwind1/article/details/128980145?spm=1001.2014.3001.5501