mybatis动态sql

If、trim、foreach

<select id="selectBooksIn" resultType="com.jt.model.Book" parameterType="java.util.List">
select * from t_mvc_book where bid in
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
List<Book> selectBooksIn(@Param("bookIds") List bookIds);

再来看下工具类

Pagebean.java

    private static final long serialVersionUID = 2422581023658455731L;

    //页码
private int page=;
//每页显示记录数
private int rows=;
//总记录数
private int total=;
//是否分页
private boolean isPagination=true;
//上一次的请求路径
private String url;
//获取所有的请求参数
private Map<String,String[]> map; public PageBean() {
super();
} //设置请求参数
public void setRequest(HttpServletRequest req) {
String page=req.getParameter("page");
String rows=req.getParameter("rows");
String pagination=req.getParameter("pagination");
this.setPage(page);
this.setRows(rows);
this.setPagination(pagination);
this.url=req.getContextPath()+req.getServletPath();
this.map=req.getParameterMap();
}
public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} public Map<String, String[]> getMap() {
return map;
} public void setMap(Map<String, String[]> map) {
this.map = map;
} public int getPage() {
return page;
} public void setPage(int page) {
this.page = page;
} public void setPage(String page) {
if(null!=page&&!"".equals(page.trim()))
this.page = Integer.parseInt(page);
} public int getRows() {
return rows;
} public void setRows(int rows) {
this.rows = rows;
} public void setRows(String rows) {
if(null!=rows&&!"".equals(rows.trim()))
this.rows = Integer.parseInt(rows);
} public int getTotal() {
return total;
} public void setTotal(int total) {
this.total = total;
} public void setTotal(String total) {
this.total = Integer.parseInt(total);
} public boolean isPagination() {
return isPagination;
} public void setPagination(boolean isPagination) {
this.isPagination = isPagination;
} public void setPagination(String isPagination) {
if(null!=isPagination&&!"".equals(isPagination.trim()))
this.isPagination = Boolean.parseBoolean(isPagination);
} /**
* 获取分页起始标记位置
* @return
*/
public int getStartIndex() {
//(当前页码-1)*显示记录数
return (this.getPage()-)*this.rows;
} /**
* 末页
* @return
*/
public int getMaxPage() {
int totalpage=this.total/this.rows;
if(this.total%this.rows!=)
totalpage++;
return totalpage;
} /**
* 下一页
* @return
*/
public int getNextPage() {
int nextPage=this.page+;
if(this.page>=this.getMaxPage())
nextPage=this.getMaxPage();
return nextPage;
} /**
* 上一页
* @return
*/
public int getPreivousPage() {
int previousPage=this.page-;
if(previousPage<)
previousPage=;
return previousPage;
} @Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
+ "]";
}

StringUtils

public class StringUtils {

    public static String toLikeStr(String str) {
return "%"+str+"%";
} }

2、模糊查询

#{…}
${…}
Concat

注意:#{...}自带引号,${...}有sql注入的风险

<select id="selectBooksLike1" resultType="com.jt.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like #{bname}
</select>
<select id="selectBooksLike2" resultType="com.jt.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like '${bname}'
</select>
<select id="selectBooksLike3" resultType="com.jt.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>
List<Book> selectBooksLike1(@Param("bname")String bname);
List<Book> selectBooksLike2(@Param("bname")String bname);
List<Book> selectBooksLike3(@Param("bname")String bname);

查询返回结果集的处理

resultMap:适合使用返回值是自定义实体类的情况

resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型

3.1 使用resultMap返回自定义类型集合

3.2 使用resultType返回List<T>

3.3 使用resultType返回单个对象

3.4 使用resultType返回List<Map>,适用于多表查询返回结果集

3.5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集

<select id="list1" resultMap="BaseResultMap">
select * from t_mvc_book
</select>
<select id="list2" resultType="com.jt.model.Book">
select * from t_mvc_book
</select>
<select id="list3" resultType="com.jt.model.Book" parameterType="com.jt.model.vo.BookVo">
select * from t_mvc_book where bid in
<foreach collection="bookIds" item="bid" open="(" close=")" separator=",">
#{bid}
</foreach>
</select>
<select id="list4" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book where bid in
<foreach collection="bookIds" item="bid" open="(" close=")" separator=",">
#{bid}
</foreach>
</select>
<select id="list5" resultType="java.util.Map">
select * from t_mvc_book where bid = #{bid}
</select>
public void list() {
// List<Book> books = this.bookService.list1();
// List<Book> books = this.bookService.list2();
List list=new ArrayList();
list.add();
list.add();
list.add();
// BookVo bookVo=new BookVo();
// bookVo.setBookIds(list);
// List<Book> books = this.bookService.list3(bookVo);
//
//
// for (Book b : books) {
// System.out.println(b);
// } // Map map=new HashMap();
// map.put("bookIds",list);
// List<Map> mapList = this.bookService.list4(map);
// for (Map m : mapList) {
// System.out.println(m);
//
// }
// map.put("bid",1);
// System.out.println(this.bookService.list5(map)); }

分页查询

为什么要重写mybatis的分页?

Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的分页基本上是没有用的

使用分页插件步奏

1、导入pom依赖

2、Mybatis.cfg.xml配置拦截器

3、使用PageHelper进行分页

4、处理分页结果

pom依赖

<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.</version>
</dependency>

Mybatis.cfg.xml配置拦截器

<plugins>
<!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>

使用分页插件

<select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>

Mapper层

List<Map> listPager(Map map);

Service层

List<Map> listPager(Map map, PageBean pageBean);
@Override
public List<Map> listPager(Map map, PageBean pageBean) {
if(pageBean != null && pageBean.isPagination()){
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
}
List<Map> list = bookMapper.listPager(map);
if(pageBean != null && pageBean.isPagination()){
PageInfo pageInfo = new PageInfo(list);
System.out.println("页码:"+pageInfo.getPageNum());
System.out.println("页大小:"+pageInfo.getPageSize());
System.out.println("总记录:"+pageInfo.getTotal());
pageBean.setTotal(pageInfo.getTotal()+"");
}
return list;
}

特殊字符处理

>(&gt;)
<(&lt;)
&(&amp;)
空格(&nbsp;)
<![CDATA[ <= ]]>

相关代码配置

<select id="list6" resultType="com.jt.model.Book" parameterType="com.jt.model.vo.BookVo">
select * from t_mvc_book where <![CDATA[ price >#{min} and price <#{max} ]]>
</select>
<select id="list7" resultType="com.jt.model.Book" parameterType="com.jt.model.vo.BookVo">
select * from t_mvc_book where &gt;#{min} and price &lt;#{max}
</select>

Mybatis的动态sql以及分页的更多相关文章

  1. 利用MyBatis的动态SQL特性抽象统一SQL查询接口

    1. SQL查询的统一抽象 MyBatis制动动态SQL的构造,利用动态SQL和自定义的参数Bean抽象,可以将绝大部分SQL查询抽象为一个统一接口,查询参数使用一个自定义bean继承Map,使用映射 ...

  2. Mybatis中动态SQL语句中的parameterType不同数据类型的用法

    Mybatis中动态SQL语句中的parameterType不同数据类型的用法1. 简单数据类型,    此时#{id,jdbcType=INTEGER}中id可以取任意名字如#{a,jdbcType ...

  3. MyBatis的动态SQL详解

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它 ...

  4. Mybatis解析动态sql原理分析

    前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...

  5. mybatis 使用动态SQL

    RoleMapper.java public interface RoleMapper { public void add(Role role); public void update(Role ro ...

  6. MyBatis框架——动态SQL、缓存机制、逆向工程

    MyBatis框架--动态SQL.缓存机制.逆向工程 一.Dynamic SQL 为什么需要动态SQL?有时候需要根据实际传入的参数来动态的拼接SQL语句.最常用的就是:where和if标签 1.参考 ...

  7. 使用Mybatis实现动态SQL(一)

    使用Mybatis实现动态SQL 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 写在前面:        *本章节适合有Mybatis基础者观看* 前置讲解 我现在写一个查询全部的 ...

  8. MyBatis探究-----动态SQL详解

    1.if标签 接口中方法:public List<Employee> getEmpsByEmpProperties(Employee employee); XML中:where 1=1必不 ...

  9. mybatis中的.xml文件总结——mybatis的动态sql

    resultMap resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功. 如果sql查询字段名和pojo的属性名不一致,可以通过re ...

随机推荐

  1. Python项目搬迁,快捷导出环境依赖包到requirements.txt

    项目搬迁的时候,需要把当前的环境依赖包导出,然后到部署项目的服务器上安装依赖. 我们可以通过下面的命令执行,把依赖包导出到requirements.txt文件里. 生成requirements.txt ...

  2. spring cloud学习与思考——总起篇

    接下来就spring cloud( Spring Boot 2.0版本)写一个系列,一方面加深记忆理解,做个日志,另一个方面,借这个方式跟朋友们沟通交流. 1.Spring boot是Spring的一 ...

  3. Ubuntu Server 上使用Docker Compose 部署Nexus(图文教程)

    场景 Docker-Compose简介与Ubuntu Server 上安装Compose: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...

  4. JavaScript高阶函数(Heigher-order function)

    概念 <javascript设计模式和开发实践>中定义 函数既可作为参数被传递,也可以作为返回值输出 满足以下条件: 接受一个或多个函数作为输入 输出一个函数 高阶函数一般是那些函数型包含 ...

  5. 短信相关的AT指令以及信令

    本文链接:https://blog.csdn.net/sjz4860402/article/details/78552756 此次的短信AT指令和信令从以下几个方面介绍: 一 . 短信AT指令的格式二 ...

  6. 【Android】Android Studio NDK 开发

    Android Studio NDK 开发 记录在Android Studio中NDK简单开发的步骤 用到的Android Studio版本为3.5. 配置NDK 下载NDK 一般在SDK下已经有自带 ...

  7. 前端开发规范:4-JS

    ESLint 使用ESLint的standard规范来编写js代码 更多参考: https://github.com/standard/standard/blob/master/docs/README ...

  8. 设计冲刺Design Sprint - 阅读记录

    改进团队流程: 审查了头脑风暴 - brain storming的成果,真正付诸实践并且获得成功的想法并不是来自大喊大叫的头脑风暴.而是来自静下心来的一次思考. 1. 搭建舞台 在开始设计冲刺之前,你 ...

  9. 测试工程师如何使用 CODING 进行测试管理

    CODING 为您的企业提供从概念到软件开发再到产品发布的全流程全周期软件研发管理,为您的研发团队提供全程助力,帮助研发团队捋清需求.不断迭代.快速反馈并能实时追踪项目进度直到完成.同时 CODING ...

  10. 获取redis中所有的key,清空整个 Redis 服务器的数据

    获取 redis 中所有的 key 可用使用 *. redis 127.0.0.1:6379> KEYS * Redis Flushall 命令用于清空整个 Redis 服务器的数据(删除所有数 ...