Mybatis动态sql及分页

1.mybatis动态sql
1.1 if
1.2 trim
1.3 foreach
遍历集合,批量查询、通常用于in关键字
1.4 其他
choose/set/where
2.模糊查询(3种方式)

2.1 参数中直接加入%%
2.2 使用${...}代替#{...}(不建议使用该方式,有SQL注入风险)
      关键:#{...}与${...}区别?
      参数类型为字符串,#会在前后加单引号['],$则直接插入值
      注:
      1) mybatis中使用OGNL表达式传递参数
      2) 优先使用#{...}
      3) ${...}方式存在SQL注入风险
2.3 SQL字符串拼接CONCAT

3.查询返回结果集
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
3.1 使用resultMap返回自定义类型集合
3.2 使用resultType返回List
3.3 使用resultType返回单个对象
3.4 使用resultType返回List,适用于多表查询返回结果集
3.5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
4.分页查询

为什么要重写mybatis的分页?
Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的
分页基本上是没有用的 struts拦截器
定义一个拦截器类
invoke
sysout(“action方法被调用前执行的功能”)
method.invoke
sysout(“action方法被调用后执行的功能”)

struts-sy.xml
    将拦截器的类申明到interceptors
    引用拦截器
    <action>
        <interceptor-ref>

4.1 导入分页插件

   <dependency>
     <groupId>com.github.pagehelper</groupId>
     <artifactId>pagehelper</artifactId>
     <version>5.1.2</version>
   </dependency>
4.2 将pagehelper插件配置到mybatis中
   <!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
   <plugin interceptor="com.github.pagehelper.PageInterceptor">
   </plugin>

4.3 在你需要进行分页的Mybatis方法前调用PageHelper.startPage静态方法即可,紧跟在这个方法后的第一个Mybatis查询方法会被进行分页
   //设置分页处理
   if (null != pageBean && pageBean.isPaginate()) {
     PageHelper.startPage(pageBean.getCurPage(), pageBean.getPageRecord());
   }
   
4.4 获取分页信息(二种方式)
  
 4.4.1 使用插件后,查询实际返回的是Page<E>,而非List<E>,Page继承了ArrayList,同时还包含分页相关的信息
      Page<Book> page = (Page<Book>)list;
      System.out.println("页码:" + page.getPageNum());
      System.out.println("页大小:" + page.getPageSize());
      System.out.println("总记录:" + page.getTotal());
 4.4.2 使用PageInfo
      PageInfo pageInfo = new PageInfo(list);
      System.out.println("页码:" + pageInfo.getPageNum());
      System.out.println("页大小:" + pageInfo.getPageSize());
      System.out.println("总记录:" + pageInfo.getTotal());

5.特殊字符处理
>(>)
<(<)
&(&)
空格( )

<![CDATA[ <= ]]>

二、案例

BookMapper.xml

<select id="selectBooksIn" resultType="com.pyx.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>

BookMapper

List<Book> selectBooksIn(@Param("bookIds") List bookIds);

Pagebean

  private static final long serialVersionUID = 1L;
 
    //页码
    private int page=1;
    //每页显示记录数
    private int rows=10;
    //总记录数
    private int total=0;
    //是否分页
    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()-1)*this.rows;
    }
    
    /**
     * 末页
     * @return
     */
    public int getMaxPage() {
        int totalpage=this.total/this.rows;
        if(this.total%this.rows!=0)
            totalpage++;
        return totalpage;
    }
    
    /**
     * 下一页
     * @return
     */
    public int getNextPage() {
        int nextPage=this.page+1;
        if(this.page>=this.getMaxPage())
            nextPage=this.getMaxPage();
        return nextPage;
    }
    
    /**
     * 上一页
     * @return
     */
    public int getPreivousPage() {
        int previousPage=this.page-1;
        if(previousPage<1)
            previousPage=1;
        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+"%";
    }
    )

三、模糊查询

#{…}
${…}
Concat

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

<select id="selectBooksLike1" resultType="com.pyx.model.Book" parameterType="java.lang.String">
  select * from t_mvc_book where bname like #{bname}
</select>
<select id="selectBooksLike2" resultType="com.pyx.model.Book" parameterType="java.lang.String">
  select * from t_mvc_book where bname like '${bname}'
</select>
<select id="selectBooksLike3" resultType="com.pyx.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);


  <select id="list1" resultMap="BaseResultMap">
    select * from t_mvc_book
  </select>
  <select id="list2" resultType="com.pyx.model.Book">
    select * from t_mvc_book
  </select>
  <select id="list3" resultType="com.pyx.model.Book" parameterType="com.pyx.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 list=new ArrayList();
        list.add(1);
        list.add(12);
        list.add(16);
}

四、分页查询
pom.xml

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

Mybatis.cfg.xml


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

BookMapper.xml

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

BookMapper


List<Map> listPager(Map map);

Service

List<Map> listPager(Map map, PageBean pageBean);


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;
    )

特殊字符

<select id="list6" resultType="com.pyx.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.pyx.model.Book" parameterType="com.jt.model.vo.BookVo">
    select * from t_mvc_book where &gt;#{min} and price &lt;#{max}
  </select>
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值