• Mybatis—动态sql和分页


    目录

    简介:

    一、foreach标签

    二、模糊查询

    三、结果集的处理

    四、第三方插件继承Mybatis使用

    五、特殊字符处理

    六、总结


    简介:

    动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

    使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。

    MyBatis 的真正强大在于它的语句映射,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 致力于减少使用成本,让用户能更专注于 SQL 代码。 

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

    一、foreach标签

    1、BookMapper.xml

    1. <select id="selectByIn" resultMap="BaseResultMap" parameterType="java.util.List" >
    2. select
    3. <include refid="Base_Column_List" />
    4. from t_mvc_book
    5. where bid in
    6. <foreach collection="bookIds" open="(" close=")" separator="," item="bid">
    7. #{bid}
    8. foreach>
    9. select>

    2、BookMapper

    1. // 通过in关键字进行查询:讲解foreach 标签的使用
    2. // 如果说参数是非实体类(book,Order,....),那么急的加上注解 @param,bookIds是对应collection属性的
    3. List selectByIn(@Param("bookIds") List bookIds);

    3、BookBizImpl

    1. @Override
    2. public List selectByIn(List bookIds) {
    3. return bookMapper.selectByIn(bookIds);
    4. }

     4、BookBiz

    List selectByIn(List bookIds);
    

    5、BookBizImplTest

    1. @Test
    2. public void selectByIn() {
    3. List bookIds = Arrays.asList(new Integer[]{31, 32, 33, 34});
    4. bookBiz.selectByIn(bookIds).forEach(System.out::println);
    5. }

    二、模糊查询

    1、test1

    BookBiz

    public List<Book> selectBooksLike1(String bname);
    

    BookBizImpl

    1. @Override
    2. public List selectBooksLike1(String bname) {
    3. return bookMapper.selectBooksLike1(bname);
    4. }

    BookMapper.xml

    1. <select id="selectBooksLike1" resultType="com.liaoxin.model.Book" parameterType="java.lang.String">
    2. select * from t_mvc_book where bname like #{bname}
    3. select>

    BookMapper.java

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

    BookBizImplTest

    1. @Test
    2. public void selectBooksLike1() {
    3. bookBiz.selectBooksLike1("%圣墟%").forEach(System.out::println);
    4. }

    2、test2

    BookBiz

    public List selectBooksLike2(String bname);
    

    BookBizImpl

    1. @Override
    2. public List selectBooksLike2(String bname) {
    3. return bookMapper.selectBooksLike2(bname);
    4. }

    BookMapper.xml

    1. <select id="selectBooksLike2" resultType="com.liaoxin.model.Book" parameterType="java.lang.String">
    2. select * from t_mvc_book where bname like '${bname}'
    3. select>

    BookMapper.java

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

    BookBizImplTest

    1. @Test
    2. public void selectBooksLike2() {
    3. bookBiz.selectBooksLike2("%圣墟%").forEach(System.out::println);
    4. }

    3、test3

    BookBiz

    public List selectBooksLike3(String bname);
    

    BookBizImpl

    1. @Override
    2. public List selectBooksLike3(String bname) {
    3. return bookMapper.selectBooksLike3(bname);
    4. }

    BookMapper.xml

    1. <select id="selectBooksLike3" resultType="com.liaoxin.model.Book" parameterType="java.lang.String">
    2. select * from t_mvc_book where bname like concat('%',#{bname},'%')
    3. select>

    BookMapper.java

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

    BookBizImplTest

    1. @Test
    2. public void selectBooksLike3() {
    3. bookBiz.selectBooksLike3("圣墟").forEach(System.out::println);
    4. }

    三、结果集的处理

    1、list1

    BookBiz

    List list1();
    

    BookBizImpl

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

    BookMapper.xml

    1. <select id="list1" resultMap="BaseResultMap">
    2. select * from t_mvc_book
    3. select>

    BookMapper.java

    1. // list1 list2的结论是,对于单表查询而言,可以用resultmap/resulttype接收,但是多表必须用resultmap接收
    2. List list1();

    BookVo

    1. package com.liaoxin.model;
    2. import java.util.List;
    3. public class BookVo extends Book{
    4. private List bookIds;
    5. public List getBookIds() {
    6. return bookIds;
    7. }
    8. public void setBookIds(List bookIds) {
    9. this.bookIds = bookIds;
    10. }
    11. }

    BookBizImplTest

    1. @Test
    2. public void list1() {
    3. bookBiz.list1().forEach(System.out::println);
    4. }

    2、list2

    BookBiz

    List list2();
    

    BookBizImpl

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

    BookMapper.xml

    1. select>
    2. <select id="list2" resultType="com.liaoxin.model.Book">
    3. select * from t_mvc_book
    4. select>

    BookMapper.java

     List list2();
    

    BookVo 

    1. package com.liaoxin.model;
    2. import java.util.List;
    3. public class BookVo extends Book{
    4. private List bookIds;
    5. public List getBookIds() {
    6. return bookIds;
    7. }
    8. public void setBookIds(List bookIds) {
    9. this.bookIds = bookIds;
    10. }
    11. }

    BookBizImplTest

    1. @Test
    2. public void list2() {
    3. bookBiz.list2().forEach(System.out::println);
    4. }

    3、list3

    BookBiz

    List list3(BookVo vo);
    

    BookBizImpl

    1. @Override
    2. public List list3(BookVo vo) {
    3. return bookMapper.list3(vo);
    4. }

    BookMapper.xml

    1. <select id="list3" resultType="com.liaoxin.model.Book" parameterType="com.liaoxin.model.BookVo">
    2. select * from t_mvc_book where bid in
    3. <foreach collection="bookIds" open="(" close=")" separator="," item="bid">
    4. #{bid}
    5. foreach>
    6. select>

    BookMapper.java

    1. // 如果要传入多个查询参数,必须以对象的方式进行传递
    2. // 举例:select * from t_mvc_book where bid in (1,2,3,4,5,6) and bname in ("圣墟","不死不休")
    3. List list3(BookVo vo);

    BookVo

    1. package com.liaoxin.model;
    2. import java.util.List;
    3. public class BookVo extends Book{
    4. private List bookIds;
    5. public List getBookIds() {
    6. return bookIds;
    7. }
    8. public void setBookIds(List bookIds) {
    9. this.bookIds = bookIds;
    10. }
    11. }

    BookBizImplTest

    1. @Test
    2. public void list3() {
    3. BookVo vo=new BookVo();
    4. vo.setBookIds(Arrays.asList(new Integer[]{31,32,33,34}));
    5. bookBiz.list3(vo).forEach(System.out::println);
    6. }

    4、list4

    BookBiz

    List list4();
    

    BookBizImpl

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

    BookMapper.xml

    1. <select id="list4" resultType="java.util.Map">
    2. select * from t_mvc_book
    3. select>

    BookMapper.java

    1. // 说明了不管返回1条数据,还是多条数据,都应该用java.util.Map进行接受
    2. // 如果是1条数据,那么返回值是Map
    3. // 如果是多条数据,那么返回值List
    4. List list4();

    BookVo

    1. package com.liaoxin.model;
    2. import java.util.List;
    3. public class BookVo extends Book{
    4. private List bookIds;
    5. public List getBookIds() {
    6. return bookIds;
    7. }
    8. public void setBookIds(List bookIds) {
    9. this.bookIds = bookIds;
    10. }
    11. }

    BookBizImplTest

    1. @Test
    2. public void list4() {
    3. bookBiz.list4().forEach(System.out::println);
    4. }

    5、list5

    BookBiz

    Map list5(Map map);
    

    BookBizImpl

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

    BookMapper.xml

    1. <select id="list5" resultType="java.util.Map" parameterType="java.util.Map">
    2. select * from t_mvc_book where bid = #{bid}
    3. select>

    BookMapper.java

    Map list5(Map map);
    

    BookVo

    1. package com.liaoxin.model;
    2. import java.util.List;
    3. public class BookVo extends Book{
    4. private List bookIds;
    5. public List getBookIds() {
    6. return bookIds;
    7. }
    8. public void setBookIds(List bookIds) {
    9. this.bookIds = bookIds;
    10. }
    11. }

    BookBizImplTest

    1. @Test
    2. public void list5() {
    3. Map map=new HashMap();
    4. map.put("bid",32);
    5. System.out.println(bookBiz.list5(map));
    6. }

    四、第三方插件继承Mybatis使用

    1、导入pom依赖

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

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

    1. <plugins>
    2. <plugin interceptor="com.github.pagehelper.PageInterceptor">
    3. plugin>
    4. plugins>

    3、使用PageHelper进行分页

    1. package com.liaoxin.util;
    2. import java.io.Serializable;
    3. import java.util.Map;
    4. import javax.servlet.http.HttpServletRequest;
    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. }

    4、处理分页结果

    BookBiz

    List listPager(Map map, PageBean pageBean);
    

    BookMapper.java

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

    BookMapper.xml

    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>

    BookBizImpl

    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

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

    五、特殊字符处理

    1、特殊字符

    1. (>)
    2. <(<)
    3. &(&)
    4. 空格( )

    2、BookBiz

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

    3、BookBizImpl

    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. }

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

    5、BookMapper.xml

    1. <select id="list6" resultType="com.liaoxin.model.Book" parameterType="com.liaoxin.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.liaoxin.model.Book" parameterType="com.liaoxin.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>

    6、BookBizImplTest

    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.list7(vo).forEach(System.out::println);
    14. }

    六、总结

    1、MyBatis中#和$的区别

    1、#将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。
    如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by ‘111’,
    如果传入的值是id,则解析成的sql为order by “id”.
    2、$将传入的数据直接显示生成在sql中。
    如:order by u s e r i d user_iduser 
    3、id,如果传入的值是111,那么解析成sql时的值为order by user_id,
    如果传入的值是id,则解析成的sql为order by id.
    #方式能够很大程度防止sql注入。
    4、$方式无法防止Sql注入。
    5、$方式一般用于传入数据库对象,例如传入表名.
    6、一般能用#的就别用$.

    2、BookBiz 

    1. package com.liaoxin.biz;
    2. import com.liaoxin.model.Book;
    3. import com.liaoxin.model.BookVo;
    4. import com.liaoxin.util.PageBean;
    5. import org.apache.ibatis.annotations.Param;
    6. import java.util.List;
    7. import java.util.Map;
    8. public interface BookBiz {
    9. public int deleteByPrimaryKey(Integer bid);
    10. public Book selectByPrimaryKey(Integer bid);
    11. public List selectByIn(List bookIds);
    12. public List selectBooksLike1(String bname);
    13. public List selectBooksLike2(String bname);
    14. public List selectBooksLike3(String bname);
    15. List list1();
    16. List list2();
    17. List list3(BookVo vo);
    18. List list4();
    19. Map list5(Map map);
    20. List listPager(Map map, PageBean pageBean);
    21. List list6(BookVo bookVo);
    22. List list7(BookVo bookVo);
    23. }

    3、BookBizImpl

    1. package com.liaoxin.biz.impl;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.liaoxin.biz.BookBiz;
    5. import com.liaoxin.mapper.BookMapper;
    6. import com.liaoxin.model.Book;
    7. import com.liaoxin.model.BookVo;
    8. import com.liaoxin.util.PageBean;
    9. import java.util.List;
    10. import java.util.Map;
    11. public class BookBizImpl implements BookBiz {
    12. private BookMapper bookMapper;
    13. // alt+insert 快速提供set/get/tostring/构造方法
    14. // alt+enter 快速构建实现类,填充代码的前半部分 ctrl+1
    15. public BookMapper getBookMapper() {
    16. return bookMapper;
    17. }
    18. public void setBookMapper(BookMapper bookMapper) {
    19. this.bookMapper = bookMapper;
    20. }
    21. @Override
    22. public int deleteByPrimaryKey(Integer bid) {
    23. return bookMapper.deleteByPrimaryKey(bid);
    24. }
    25. @Override
    26. public Book selectByPrimaryKey(Integer bid) {
    27. return bookMapper.selectByPrimaryKey(bid);
    28. }
    29. @Override
    30. public List selectByIn(List bookIds) {
    31. return bookMapper.selectByIn(bookIds);
    32. }
    33. @Override
    34. public List selectBooksLike1(String bname) {
    35. return bookMapper.selectBooksLike1(bname);
    36. }
    37. @Override
    38. public List selectBooksLike2(String bname) {
    39. return bookMapper.selectBooksLike2(bname);
    40. }
    41. @Override
    42. public List selectBooksLike3(String bname) {
    43. return bookMapper.selectBooksLike3(bname);
    44. }
    45. @Override
    46. public List list1() {
    47. return bookMapper.list1();
    48. }
    49. @Override
    50. public List list2() {
    51. return bookMapper.list2();
    52. }
    53. @Override
    54. public List list3(BookVo vo) {
    55. return bookMapper.list3(vo);
    56. }
    57. @Override
    58. public List list4() {
    59. return bookMapper.list4();
    60. }
    61. @Override
    62. public Map list5(Map map) {
    63. return bookMapper.list5(map);
    64. }
    65. @Override
    66. public List listPager(Map map, PageBean pageBean) {
    67. // pageHelper分页插件相关的代码
    68. if(pageBean!=null&&pageBean.isPagination()){
    69. PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
    70. }
    71. List maps = bookMapper.listPager(map);
    72. if(pageBean!=null&&pageBean.isPagination()){
    73. // 处理查询结果的前提是需要分页,是需要分页的
    74. PageInfo info = new PageInfo(maps);
    75. pageBean.setTotal(info.getTotal()+"");
    76. }
    77. return maps;
    78. }
    79. @Override
    80. public List list6(BookVo bookVo) {
    81. return bookMapper.list6(bookVo);
    82. }
    83. @Override
    84. public List list7(BookVo bookVo) {
    85. return bookMapper.list7(bookVo);
    86. }
    87. }

    4、BookMaper.xml

    1. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    2. <mapper namespace="com.liaoxin.mapper.BookMapper" >
    3. <resultMap id="BaseResultMap" type="com.liaoxin.model.Book" >
    4. <constructor >
    5. <idArg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
    6. <arg column="bname" jdbcType="VARCHAR" javaType="java.lang.String" />
    7. <arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
    8. constructor>
    9. resultMap>
    10. <sql id="Base_Column_List" >
    11. bid, bname, price
    12. sql>
    13. <select id="selectByPrimaryKey" resultType="com.liaoxin.model.Book" parameterType="java.lang.Integer" >
    14. select
    15. <include refid="Base_Column_List" />
    16. from t_mvc_book
    17. where bid = #{bid,jdbcType=INTEGER}
    18. select>
    19. <select id="selectByIn" resultType="com.liaoxin.model.Book" parameterType="java.util.List" >
    20. select
    21. <include refid="Base_Column_List" />
    22. from t_mvc_book
    23. where bid in
    24. <foreach collection="bookIds" open="(" close=")" separator="," item="bid">
    25. #{bid}
    26. foreach>
    27. select>
    28. <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    29. delete from t_mvc_book
    30. where bid = #{bid,jdbcType=INTEGER}
    31. delete>
    32. <insert id="insert" parameterType="com.liaoxin.model.Book" >
    33. insert into t_mvc_book (bid, bname, price
    34. )
    35. values (#{bid,jdbcType=INTEGER}, #{bname,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
    36. )
    37. insert>
    38. <insert id="insertSelective" parameterType="com.liaoxin.model.Book" >
    39. insert into t_mvc_book
    40. <trim prefix="(" suffix=")" suffixOverrides="," >
    41. <if test="bid != null" >
    42. bid,
    43. if>
    44. <if test="bname != null" >
    45. bname,
    46. if>
    47. <if test="price != null" >
    48. price,
    49. if>
    50. trim>
    51. <trim prefix="values (" suffix=")" suffixOverrides="," >
    52. <if test="bid != null" >
    53. #{bid,jdbcType=INTEGER},
    54. if>
    55. <if test="bname != null" >
    56. #{bname,jdbcType=VARCHAR},
    57. if>
    58. <if test="price != null" >
    59. #{price,jdbcType=REAL},
    60. if>
    61. trim>
    62. insert>
    63. <update id="updateByPrimaryKeySelective" parameterType="com.liaoxin.model.Book" >
    64. update t_mvc_book
    65. <set >
    66. <if test="bname != null" >
    67. bname = #{bname,jdbcType=VARCHAR},
    68. if>
    69. <if test="price != null" >
    70. price = #{price,jdbcType=REAL},
    71. if>
    72. set>
    73. where bid = #{bid,jdbcType=INTEGER}
    74. update>
    75. <update id="updateByPrimaryKey" parameterType="com.liaoxin.model.Book" >
    76. update t_mvc_book
    77. set bname = #{bname,jdbcType=VARCHAR},
    78. price = #{price,jdbcType=REAL}
    79. where bid = #{bid,jdbcType=INTEGER}
    80. update>
    81. <select id="selectBooksLike1" resultType="com.liaoxin.model.Book" parameterType="java.lang.String">
    82. select * from t_mvc_book where bname like #{bname}
    83. select>
    84. <select id="selectBooksLike2" resultType="com.liaoxin.model.Book" parameterType="java.lang.String">
    85. select * from t_mvc_book where bname like '${bname}'
    86. select>
    87. <select id="selectBooksLike3" resultType="com.liaoxin.model.Book" parameterType="java.lang.String">
    88. select * from t_mvc_book where bname like concat('%',#{bname},'%')
    89. select>
    90. <select id="list1" resultMap="BaseResultMap">
    91. select * from t_mvc_book
    92. select>
    93. <select id="list2" resultType="com.liaoxin.model.Book">
    94. select * from t_mvc_book
    95. select>
    96. <select id="list3" resultType="com.liaoxin.model.Book" parameterType="com.liaoxin.model.BookVo">
    97. select * from t_mvc_book where bid in
    98. <foreach collection="bookIds" open="(" close=")" separator="," item="bid">
    99. #{bid}
    100. foreach>
    101. select>
    102. <select id="list4" resultType="java.util.Map">
    103. select * from t_mvc_book
    104. select>
    105. <select id="list5" resultType="java.util.Map" parameterType="java.util.Map">
    106. select * from t_mvc_book where bid = #{bid}
    107. select>
    108. <select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
    109. select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
    110. select>
    111. <select id="list6" resultType="com.liaoxin.model.Book" parameterType="com.liaoxin.model.BookVo">
    112. select * from t_mvc_book
    113. <where>
    114. <if test="null != min and min != ''">
    115. if>
    116. <if test="null != max and max != ''">
    117. price ]]>
    118. if>
    119. where>
    120. select>
    121. <select id="list7" resultType="com.liaoxin.model.Book" parameterType="com.liaoxin.model.BookVo">
    122. select * from t_mvc_book
    123. <where>
    124. <if test="null != min and min != ''">
    125. and #{min} < price
    126. if>
    127. <if test="null != max and max != ''">
    128. and #{max} > price
    129. if>
    130. where>
    131. select>
    132. mapper>

    5、BookMapper.java

    1. package com.liaoxin.mapper;
    2. import com.liaoxin.model.Book;
    3. import com.liaoxin.model.BookVo;
    4. import org.apache.ibatis.annotations.Param;
    5. import java.util.List;
    6. import java.util.Map;
    7. public interface BookMapper {
    8. int deleteByPrimaryKey(Integer bid);
    9. int insert(Book record);
    10. int insertSelective(Book record);
    11. Book selectByPrimaryKey(Integer bid);
    12. int updateByPrimaryKeySelective(Book record);
    13. int updateByPrimaryKey(Book record);
    14. // 通过in关键字进行查询:讲解foreach 标签的使用
    15. // 如果说参数是非实体类(book,Order,....),那么急的加上注解 @param,bookIds是对应collection属性的
    16. List selectByIn(@Param("bookIds") List bookIds);
    17. List selectBooksLike1(@Param("bname") String bname);
    18. List selectBooksLike2(@Param("bname") String bname);
    19. List selectBooksLike3(@Param("bname") String bname);
    20. // list1 list2的结论是,对于单表查询而言,可以用resultmap/resulttype接收,但是多表必须用resultmap接收
    21. List list1();
    22. List list2();
    23. // 如果要传入多个查询参数,必须以对象的方式进行传递
    24. // 举例:select * from t_mvc_book where bid in (1,2,3,4,5,6) and bname in ("圣墟","不死不休")
    25. List list3(BookVo vo);
    26. // 说明了不管返回1条数据,还是多条数据,都应该用java.util.Map进行接受
    27. // 如果是1条数据,那么返回值是Map
    28. // 如果是多条数据,那么返回值List
    29. List list4();
    30. Map list5(Map map);
    31. // 利用第三方插件进行分页
    32. List listPager(Map map);
    33. /**
    34. * 处理特殊字符
    35. * @param bookVo
    36. * @return
    37. */
    38. List list6(BookVo bookVo);
    39. /**
    40. * 处理特殊字符
    41. * @param bookVo
    42. * @return
    43. */
    44. List list7(BookVo bookVo);
    45. }

    6、BookBizImplTest

    1. package com.liaoxin.biz.impl;
    2. import com.liaoxin.biz.BookBiz;
    3. import com.liaoxin.mapper.BookMapper;
    4. import com.liaoxin.model.BookVo;
    5. import com.liaoxin.util.PageBean;
    6. import com.liaoxin.util.SessionUtil;
    7. import org.apache.ibatis.session.SqlSession;
    8. import org.junit.After;
    9. import org.junit.Before;
    10. import org.junit.Test;
    11. import org.junit.runner.RunWith;
    12. import java.util.Arrays;
    13. import java.util.HashMap;
    14. import java.util.List;
    15. import java.util.Map;
    16. import static org.junit.Assert.*;
    17. public class BookBizImplTest {
    18. private BookBizImpl bookBiz;
    19. private SqlSession sqlSession;
    20. @Before
    21. public void setUp() throws Exception {
    22. System.out.println("初始化方法");
    23. BookBizImpl bookBiz =new BookBizImpl();
    24. // 工具类中获取session对象
    25. sqlSession = SessionUtil.openSession();
    26. // 从session对象中获取Mapper对象
    27. BookMapper mapper = sqlSession.getMapper(BookMapper.class);
    28. bookBiz.setBookMapper(mapper);
    29. this.bookBiz=bookBiz;
    30. }
    31. @After
    32. public void tearDown() throws Exception {
    33. System.out.println("方法测试结束");
    34. sqlSession.commit();
    35. sqlSession.close();
    36. }
    37. @Test
    38. public void deleteByPrimaryKey() {
    39. bookBiz.deleteByPrimaryKey(44);
    40. }
    41. @Test
    42. public void selectByPrimaryKey() {
    43. System.out.println("测试的业务方法");
    44. // System.out.println(bookBiz.getBookMapper());
    45. System.out.println(bookBiz.selectByPrimaryKey(44));
    46. }
    47. @Test
    48. public void test3() {
    49. int[] ints={};
    50. // 将数组变成字符串 1,2,3,4,5,6
    51. StringBuffer sb=new StringBuffer();
    52. for (int i:ints){
    53. sb.append(",").append(i);
    54. }
    55. String s=sb.toString();
    56. System.out.println(s.substring(1));
    57. }
    58. @Test
    59. public void getBookMapper() {
    60. }
    61. @Test
    62. public void setBookMapper() {
    63. }
    64. @Test
    65. public void selectByIn() {
    66. List bookIds = Arrays.asList(new Integer[]{31, 32, 33, 34});
    67. bookBiz.selectByIn(bookIds).forEach(System.out::println);
    68. }
    69. @Test
    70. public void selectBooksLike1() {
    71. bookBiz.selectBooksLike1("%圣墟%").forEach(System.out::println);
    72. }
    73. @Test
    74. public void selectBooksLike2() {
    75. bookBiz.selectBooksLike2("%圣墟%").forEach(System.out::println);
    76. }
    77. @Test
    78. public void selectBooksLike3() {
    79. bookBiz.selectBooksLike3("圣墟").forEach(System.out::println);
    80. }
    81. @Test
    82. public void list1() {
    83. bookBiz.list1().forEach(System.out::println);
    84. }
    85. @Test
    86. public void list2() {
    87. bookBiz.list2().forEach(System.out::println);
    88. }
    89. @Test
    90. public void list3() {
    91. BookVo vo=new BookVo();
    92. vo.setBookIds(Arrays.asList(new Integer[]{31,32,33,34}));
    93. bookBiz.list3(vo).forEach(System.out::println);
    94. }
    95. @Test
    96. public void list4() {
    97. bookBiz.list4().forEach(System.out::println);
    98. }
    99. @Test
    100. public void list5() {
    101. Map map=new HashMap();
    102. map.put("bid",32);
    103. System.out.println(bookBiz.list5(map));
    104. }
    105. @Test
    106. public void listPager() {
    107. Map map=new HashMap();
    108. map.put("bname","圣墟");
    109. // bookBiz.listPager(map).forEach(System.out::println);
    110. // 查询出第二页的20条数据
    111. PageBean pageBean = new PageBean();
    112. pageBean.setPage(2);
    113. pageBean.setRows(20);
    114. bookBiz.listPager(map,pageBean).forEach(System.out::println);
    115. }
    116. @Test
    117. public void list6() {
    118. BookVo vo=new BookVo();
    119. vo.setMax(45);
    120. vo.setMin(35);
    121. bookBiz.list6(vo).forEach(System.out::println);
    122. }
    123. @Test
    124. public void list7() {
    125. BookVo vo=new BookVo();
    126. vo.setMax(45);
    127. vo.setMin(35);
    128. bookBiz.list7(vo).forEach(System.out::println);
    129. }
    130. }

  • 相关阅读:
    【JS 的数据类型】
    CSDN21天学习挑战赛——封装(06)
    【机器学习】随机种子Random Seed介绍(在Python、Pytorch、TensorFlow中的设置代码汇总)
    [BAT-表姐御用02tree命令】提取目录文件夹及其子文件后,tree形列出
    C++游戏后端开发(魔兽世界,MMO,TrinityCore源码拆解) 教程
    如何应对老板需求?
    内边距(padding会影响盒子内边距大小)
    病毒感染检测(运用BF算法)
    【每日两题】day 01 组队竞赛 & 删除公共字符
    C++演变历史
  • 原文地址:https://blog.csdn.net/qq_44247968/article/details/126298040