• Mybatis动态SQL和分页


    目录

    一、mybatis动态SQL

    二、查询返回结果集的处理

    三、第三方分页插件集成Mybatis使用 

    使用分页插件步骤 

    四、特殊字符的处理

    总结


    可参考文章👍👍icon-default.png?t=M666https://blog.csdn.net/weixin_67465673/article/details/126297192?spm=1001.2014.3001.5502IDEA使用事项:

    同一个project,尽量避免多个module取同样的类名

    一、mybatis动态SQL

    自定义MVC的时代:update t_oa_info set tilte=?,content=?,zhuciren=?,adthor=?....where id=?

    这样写的弊端:会议编辑界面infoEdit.jsp

           

           

    意味着后台MeetingInfo实体类只要title content属性值不为空,其他为空

    进一步:update t_oa_info set tilte=哈哈哈,content=夏天好热,zhuciren=讨厌夏天,adthor=null....where id=?

    我们可以用if标签

     

     foreach         BookMapper.xml 在这里面添加了查询代码

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

    模糊查询

    #{...}        ${...}        Concat

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

    BookMapper.xml 

    1. <select id="selectBooksLike1" resultType="com.xiaokun.model.Book" parameterType="java.lang.String">
    2. select * from t_mvc_book where bname like #{bname}
    3. </select>
    4. <select id="selectBooksLike2" resultType="com.xiaokun.model.Book" parameterType="java.lang.String">
    5. select * from t_mvc_book where bname like '${bname}'
    6. </select>
    7. <select id="selectBooksLike3" resultType="com.xiaokun.model.Book" parameterType="java.lang.String">
    8. select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
    9. </select>

    BookMapper.java

    List selectBooksLike1(@Param("bname") String bname);
    
    List selectBooksLike2(@Param("bname") String bname);
    
    List selectBooksLike3(@Param("bname") String bname)
    

    MyBatis中 #  和  $ 的区别 
     1.# 将传入的数据当成一个字符串,会对自动传入的数据加一个双引号

           如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by '111', 
           如果传入的值是id,则解析成的sql为order by "id".

    2. $ 将传入的数据直接显示生成在sql中
       如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id,
           如果传入的值是id,则解析成的sql为order by id.
     
    3. # 方式能够很大程度防止sql注入
     
    4. $ 方式无法防止Sql注入
     
    5. $ 方式一般用于传入数据库对象,例如传入表名. 
     
    6. 一般能用#的就别用$.
     

    二、查询返回结果集的处理

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

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

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

    3.2 使用resultType返回List

    3.3 使用resultType返回单个对象

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

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

    在自定义mvc中的
    baseDao
        executeQuery-->List    -->单表查询  ---->Mybatis中的ResultType
        executeQuery --->List   ->多表查询--->Mybatis中的ResultMap

    如果是单表的情况下,ResultType与ResultMap都可以使用

    BookMapper.xml

    1. <select id="list1" resultMap="BaseResultMap">
    2. select * from t_mvc_book
    3. </select>
    4. <select id="list2" resultType="com.jwj.model.Book">
    5. select * from t_mvc_book
    6. </select>
    7. <select id="list3" resultType="com.jwj.model.Book" parameterType="com.jwj.model.BookVo">
    8. select * from t_mvc_book where bid in
    9. <foreach collection="bookIds" open="(" close=")" separator="," item="bid">
    10. #{bid}
    11. </foreach>
    12. </select>
    13. <select id="list4" resultType="java.util.Map">
    14. select * from t_mvc_book
    15. </select>
    16. <select id="list5" resultType="java.util.Map" parameterType="java.util.Map">
    17. select * from t_mvc_book where bid = #{bid}
    18. </select>

    BookMapper.java

    1. // list1 list2的结论是:对于单表查询而言,可以用ResultMap/ResultType接收,但是多表必须用ResultMap接受
    2. List list1();
    3. List list2();
    4. // 如果要传入多个查询参数,必须以对象的方式进行传递
    5. // 举例:select * fromt_mvc_book where bid in (1,2,3,4,5,6) and bname in ("圣墟","不死不灭")
    6. List list3(BookVo vo);
    7. // 说明了不管返回1条数据,还是多条数据,都应该用java.util.Map进行接收
    8. //如果是1条数据,那么返回值是Map
    9. //如果是多条数据,那么返回值是List
    10. List list4();
    11. Map list5(Map map);

    BookBiz.java

    1. List list1();
    2. List list2();
    3. List list3(BookVo vo);
    4. List list4();
    5. Map list5(Map map);

    BookBizImplTest.java

    1. @Test
    2. public void list1() {
    3. bookBiz.list1().forEach(System.out::println);
    4. }
    5. @Test
    6. public void list2() {
    7. bookBiz.list2().forEach(System.out::println);
    8. }
    9. @Test
    10. public void list3() {
    11. BookVo vo=new BookVo();
    12. vo.setBookIds(Arrays.asList(new Integer[]{24,25,26,27}));
    13. bookBiz.list3(vo).forEach(System.out::println);
    14. }
    15. @Test
    16. public void list4() {
    17. bookBiz.list4().forEach(System.out::println);
    18. }
    19. @Test
    20. public void list5() {
    21. Map map=new HashMap();
    22. map.put("bid",32);
    23. System.out.println(bookBiz.list5(map));
    24. }

    list1    运行结果如图所示:

    list2        运行结果如图所示: 

    list1  list2的结论是:对于单表查询而言,可以用ResultMap/ResultType接收,但是多表必须用ResultMap接受
    list3        运行结果如图所示:

     

    如果要传入多个查询参数,必须以对象的方式进行传递
    举例:select * fromt_mvc_book where bid in (1,2,3,4,5,6) and bname in ("圣墟","不死不灭")
    list4        运行结果如图所示:

    list5        运行结果如图所示: 

    list4、list5说明了不管返回1条数据,还是多条数据,都应该用java.util.Map进行接收
    如果是1条数据,那么返回值是Map
    如果是多条数据,那么返回值是List

    三、第三方分页插件集成Mybatis使用 

    为什么要重写mybatis的分页?

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

    使用分页插件步骤 :

    导入pom依赖

    1. <dependency>
    2. <groupId>com.github.pagehelpergroupId>
    3. <artifactId>pagehelperartifactId>
    4. <version>5.1.2version>
    5. dependency>

    Mybatis.cfg.xml配置拦截器

    1. <plugins>
    2. <plugin interceptor="com.github.pagehelper.PageInterceptor">
    3. plugin>
    4. plugins>
    1. 利用第三方插件进行分页
    2. List listPager(Map map);

    使用PageHelper进行分页

            使用分页插件

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

            BookMapper.java

    1. 利用第三方插件进行分页
    2. List listPager(Map map);

            BookBizImpl.java

    1. @Override
    2. public List listPager(Map map) {
    3. return bookMapper.listPager(map);
    4. }

    测试

    1. @Test
    2. public void listPager() {
    3. Map map=new HashMap();
    4. map.put("bname","圣墟");
    5. bookBiz.listPager(map).forEach(System.out::println);
    6. }

    处理分页结果 

    要导入我们第三方插件PageBean.java

     

    1. package com.xiaokun.util;
    2. import javax.servlet.http.HttpServletRequest;
    3. import java.io.Serializable;
    4. import java.util.Map;
    5. public class PageBean implements Serializable {
    6. private static final long serialVersionUID = 2422581023658455731L;
    7. //页码
    8. private int page=1;
    9. //每页显示记录数
    10. private int rows=10;
    11. //总记录数
    12. private int total=0;
    13. //是否分页
    14. private boolean isPagination=true;
    15. //上一次的请求路径
    16. private String url;
    17. //获取所有的请求参数
    18. private Map map;
    19. public PageBean() {
    20. super();
    21. }
    22. //设置请求参数
    23. public void setRequest(HttpServletRequest req) {
    24. String page=req.getParameter("page");
    25. String rows=req.getParameter("rows");
    26. String pagination=req.getParameter("pagination");
    27. this.setPage(page);
    28. this.setRows(rows);
    29. this.setPagination(pagination);
    30. this.url=req.getContextPath()+req.getServletPath();
    31. this.map=req.getParameterMap();
    32. }
    33. public String getUrl() {
    34. return url;
    35. }
    36. public void setUrl(String url) {
    37. this.url = url;
    38. }
    39. public Map getMap() {
    40. return map;
    41. }
    42. public void setMap(Map map) {
    43. this.map = map;
    44. }
    45. public int getPage() {
    46. return page;
    47. }
    48. public void setPage(int page) {
    49. this.page = page;
    50. }
    51. public void setPage(String page) {
    52. if(null!=page&&!"".equals(page.trim()))
    53. this.page = Integer.parseInt(page);
    54. }
    55. public int getRows() {
    56. return rows;
    57. }
    58. public void setRows(int rows) {
    59. this.rows = rows;
    60. }
    61. public void setRows(String rows) {
    62. if(null!=rows&&!"".equals(rows.trim()))
    63. this.rows = Integer.parseInt(rows);
    64. }
    65. public int getTotal() {
    66. return total;
    67. }
    68. public void setTotal(int total) {
    69. this.total = total;
    70. }
    71. public void setTotal(String total) {
    72. this.total = Integer.parseInt(total);
    73. }
    74. public boolean isPagination() {
    75. return isPagination;
    76. }
    77. public void setPagination(boolean isPagination) {
    78. this.isPagination = isPagination;
    79. }
    80. public void setPagination(String isPagination) {
    81. if(null!=isPagination&&!"".equals(isPagination.trim()))
    82. this.isPagination = Boolean.parseBoolean(isPagination);
    83. }
    84. /**
    85. * 获取分页起始标记位置
    86. * @return
    87. */
    88. public int getStartIndex() {
    89. //(当前页码-1)*显示记录数
    90. return (this.getPage()-1)*this.rows;
    91. }
    92. /**
    93. * 末页
    94. * @return
    95. */
    96. public int getMaxPage() {
    97. int totalpage=this.total/this.rows;
    98. if(this.total%this.rows!=0)
    99. totalpage++;
    100. return totalpage;
    101. }
    102. /**
    103. * 下一页
    104. * @return
    105. */
    106. public int getNextPage() {
    107. int nextPage=this.page+1;
    108. if(this.page>=this.getMaxPage())
    109. nextPage=this.getMaxPage();
    110. return nextPage;
    111. }
    112. /**
    113. * 上一页
    114. * @return
    115. */
    116. public int getPreivousPage() {
    117. int previousPage=this.page-1;
    118. if(previousPage<1)
    119. previousPage=1;
    120. return previousPage;
    121. }
    122. @Override
    123. public String toString() {
    124. return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
    125. + "]";
    126. }
    127. }

    还需改动,改动好的代码⬇⬇⬇

    BookBiz.java

    List listPager(Map map, PageBean pageBean);

    BookBizImpl.java   注意这里的代码不能乱放,是固定的,后期会放到通知里面去,会进行一个Spring的整合

    1. @Override
    2. public List listPager(Map map, PageBean pageBean) {
    3. // pageHelper分页插件相关代码
    4. if(pageBean != null && pageBean.isPagination()){
    5. PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
    6. }
    7. List maps = bookMapper.listPager(map);
    8. if(pageBean != null && pageBean.isPagination()){
    9. // 处理查询结果的前提,是需要分页的
    10. PageInfo info = new PageInfo(maps);
    11. pageBean.setTotal(info.getTotal()+"");
    12. }
    13. return maps;
    14. }

    接下来进行测试:BookBizImplTest.java

    1. @Test
    2. public void listPager() {
    3. Map map=new HashMap();
    4. map.put("bname","圣墟");
    5. // bookBiz.listPager(map).forEach(System.out::println);
    6. // 查询出第二页的5条数据记录
    7. PageBean pageBean = new PageBean();
    8. pageBean.setPage(2);
    9. pageBean.setRows(5);
    10. bookBiz.listPager(map,pageBean).forEach(System.out::println);
    11. }

    四、特殊字符的处理

    >(>)           <(<)          &(&)          空格( )         

      可以一次性处理多个特殊字符     凡是被CDATA所包裹的特殊字符,都会被转义成SQL语句中的字符
     

    相关代码配置 

    1. <select id="list6" resultType="com.xiaokun.model.Book" parameterType="com.xiaokun.model.BookVo">
    2. select * from t_mvc_book
    3. <where>
    4. <if test="null != min and min != ''">
    5. if>
    6. <if test="null != max and max != ''">
    7. price ]]>
    8. if>
    9. where>
    10. select>
    11. <select id="list7" resultType="com.xiaokun.model.Book" parameterType="com.xiaokun.model.BookVo">
    12. select * from t_mvc_book
    13. <where>
    14. <if test="null != min and min != ''">
    15. and #{min} < price
    16. if>
    17. <if test="null != max and max != ''">
    18. and #{max} > price
    19. if>
    20. where>
    21. select>

     BookMapper.java

    1. /**
    2. * 处理特殊字符
    3. * @param bookVo
    4. * @return
    5. */
    6. List list6(BookVo bookVo);
    7. /**
    8. * 处理特殊字符
    9. * @param bookVo
    10. * @return
    11. */
    12. List list7(BookVo bookVo);

    BookVo.java

    1. package com.jwj.model;
    2. import java.util.List;
    3. /**
    4. * @author 敢敢
    5. * @site www.javajwj.com
    6. * @company xxx公司
    7. * @create 2022-08-13 18:46
    8. */
    9. public class BookVo extends Book {
    10. private List bookIds;
    11. private int min;
    12. private int max;
    13. public int getMax() {
    14. return max;
    15. }
    16. public void setMax(int max) {
    17. this.max = max;
    18. }
    19. public int getMin() {
    20. return min;
    21. }
    22. public void setMin(int min) {
    23. this.min = min;
    24. }
    25. // Alt+Insert键提供set,get方法
    26. public List getBookIds() {
    27. return bookIds;
    28. }
    29. public void setBookIds(List bookIds) {
    30. this.bookIds = bookIds;
    31. }
    32. }

    BookBiz.java

    1. List list6(BookVo bookVo);
    2. List list7(BookVo bookVo);

    写测试方法BookBizImpl.java

    1. @Override
    2. public List list6(BookVo bookVo) {
    3. return bookMapper.list6(bookVo);
    4. }
    5. @Override
    6. public List list7(BookVo bookVo) {
    7. return bookMapper.list7(bookVo);
    8. }

    做测试 是不是能把我的最大值和最小值查询出来

    1. @Test
    2. public void list6() {
    3. BookVo vo = new BookVo();
    4. vo.setMax(45);
    5. vo.setMin(35);
    6. bookBiz.list6(vo).forEach(System.out::println);
    7. }
    8. @Test
    9. public void list7() {
    10. BookVo vo = new BookVo();
    11. vo.setMax(45);
    12. vo.setMin(35);
    13. bookBiz.list6(vo).forEach(System.out::println);
    14. }

    总结:

    1.foreach的属性 
    Item、 Collection、open、splitrator(分隔符)、in(1,2,3,4,5)

    2.模糊查询的三种方式
    #        $        concat

    3.# 和 $ 的区别  
    # 自带双引号'',$ 不带双引号''

    # 能防止SQL与注入,$ 会有SQL的注入

    $最大的作用,传入数据库列段,数据库表名,动态列的功能

    4.ResultMap与ResultType  
     ResultTpye返回实体类对象:对应单表

    ResultMap会做Map的映射:单表、多表    一般是用多表

    5.分页github.pageHelper的分页插件 
    5.1:导入pom依赖

    5.2:Mybatis.cfg.xml中配置plugin插件

    5.3:pageHelper.startPage(page,rows)

           调用查询的方法

            对结果进行处理:PageInfo info = new PageInfo(maps)  代码是固定的

    6.特殊字符处理
    >        <        &

    6.1 CDATA的方式,凡是包裹在CDATA的区域中,都会转成SQL语句中的一部分

    6.2  >        <

  • 相关阅读:
    windows的arp响应
    9.8day59
    idea 2021.2.3版本中隐藏target和.iml文件问题的解决
    淘宝卖家为啥不退差价怎么回事 淘宝客服不退差价
    单片机——使用P3口流水点亮8位LED
    python基础05 循环 变量 函数组合案例
    VBA技术资料MF65:将十六进制值转换为RGB颜色代码
    Google Chrome 任意文件读取 (CVE-2023-4357)漏洞
    网络传输中的编码与解码
    Python与ArcGIS系列(九)自定义python地理处理工具
  • 原文地址:https://blog.csdn.net/weixin_67450855/article/details/126353149