MyBatis总结
2018-12-18 本文已影响0人
xbmchina
分页插件的使用
- pom.xml导入相关依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
- 使用方法
public PageBeanResult<ClientLog> getClientLogs(ClientLogVo clientInfo) {
try {
//1.设置分页
PageHelper.startPage(clientInfo.getPageNum(),clientInfo.getPageSize());
//2.正常的sql查询,它会自动的在后面加上相应的limit pagenum,pagesize.所以这里你写sql时,记得最后不要加分号。
List<ClientLog> list = managerRepository.getClientLogs(clientInfo);
//3.返回的结果集进行封装。可以在PageInfo里找到页码,总数,pagenum,pagesize、结果集等信息
PageInfo<ClientLog> pageInfo = new PageInfo<>(list);
PageBeanResult<ClientLog> pageBeanResult = new PageBeanResult<>();
pageBeanResult.setPageNum(pageInfo.getPageNum());
pageBeanResult.setPageSize(pageInfo.getPageSize());
pageBeanResult.setTotalSize(pageInfo.getTotal());
pageBeanResult.setList(list);
return pageBeanResult;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
in语句的使用
@Select("<script>"
+ "SELECT * FROM `user` WHERE id in "
+ "<foreach item='item' collection='list' open='(' close=')' separator=','>"
+ "#{item}"
+ "</foreach>"
+ "</script>")
List<User> listUserByIds(List<Long> ids);
set标签和where标签
//使用set标签进行动态set,要注意条件判断:没被删除的用户才可以更新数据.最后一个逗号,它会自己处理的
@Update("<script>"
+ "UPDATE `user` "
+ "<set>"
+ "<if test='nickName != null'>nick_name = #{nickName}, </if>"
+ "<if test='age != null'>age = #{age}, </if>"
+ "<if test='phoneNumber != null'>phone_number = #{phoneNumber}, </if>"
+ "<if test='birthday != null'>birthday = #{birthday}, </if>"
+ "<if test='status != null'>status = #{status}, </if>"
+ "<if test='sex != null'>sex = #{sex}, </if>"
+ "</set>"
+ "WHERE id = #{id} AND status != 'DELETE';"
+ "</script>")
void updateUser(User user);
大于号和小于号等字符的处理
原符号 < <= > >= & ' "
替换符号 < <= > >= & ' "
例如:sql如下:
create_date_time >= #{startTime} and create_date_time <= #{endTime}
或者
大于等于
<![CDATA[ >= ]]>
小于等于
<![CDATA[ <= ]]>
例如:sql如下:
create_date_time <![CDATA[ >= ]]> #{startTime} and create_date_time <![CDATA[ <= ]]> #{endTime}
设置mybatis日志打印
在配置文件中加入如下配置
logging:
level:
#Mapper所在的包
com.zero.repository: debug