Mybatis dynamic sql and paging

mybatis dynamic sql

If, trim, foreach
If: if is a condition, if the passed value is not empty, then this field can be changed; if the passed value is empty, then this field will not be seen when executing sql
**trim:* *Go to the space
Example:

<insert id="insertSelective" parameterType="com.xieminglu.model.Book" >
    insert into t_mvc_book
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="bid != null" >
        bid,
      </if>
      <if test="bname != null" >
        bname,
      </if>
      <if test="price != null" >
        price,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="bid != null" >
        #{bid,jdbcType=INTEGER},
      </if>
      <if test="bname != null" >
        #{bname,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        #{price,jdbcType=REAL},
      </if>
    </trim>
  </insert>

foreach: If the formal parameters are to be used in mapper.xml, they need to be annotated
such as: (@Param("bookIds"))

List<Book> selectBooksIn(@Param("bookIds") List bookIds);
<select id="selectBooksIn" resultType="com.javaxl.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>

Insert picture description here
Insert picture description here

Insert picture description here

Fuzzy query

mybatis三种模糊查询
#{...}
${...}
Concat
注意:#{...}自带引号,${...}有sql注入的风险
List<Book> selectBooksList1(@Param("bname") String bname);
List<Book> selectBooksList2(@Param("bname") String bname);
List<Book> selectBooksList3(@Param("bname") String bname);
<select id="selectBooksList1" resultType="com.xieminglu.model.Book" parameterType="java.lang.String">
       select * from t_mvc_book where bname like #{bname}
  </select>
  <select id="selectBooksList2" resultType="com.xieminglu.model.Book" parameterType="java.lang.String">
       select * from t_mvc_book where bname like '${bname}'
  </select>
  <select id="selectBooksList3" resultType="com.xieminglu.model.Book" parameterType="java.lang.String">
       select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
  </select>

The three query results have the same
Insert picture description here
key: the difference between # and $ in 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. 一般能用#的就别用$. 

Processing the result set returned by the query

resultMap: it is suitable to use the return value is a custom entity class
resultType: the data type suitable for the return value is non-custom, that is, the type provided by jdk

   3.1 使用resultMap返回自定义类型集合
    
   3.2 使用resultType返回List<T>

   3.3 使用resultType返回单个对象

   3.4 使用resultType返回List<Map>,适用于多表查询返回结果集
   
   3.5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
/*
    * mybatis处理结果集的五种情况
    * */
    
    /**
     * 使用resultMap返回自定义类型集合
     * @return
     */
    List<Book> list1();

    /**
     * 使用resultType返回List<T>
     * @return
     */
    List<Book> list2();

    /**
     * 使用resultType返回单个对象
     * @return
     */
    List<Book> list3(BookVo bookVo);

    /**
     * 使用resultType返回List<Map>,适用于多表查询返回结果集
     * @return
     */
    List<Map> list4(Map map);

    /**
     * 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
     * @return
     */
    Map list5(Map book);
 <select id="list1" resultMap="BaseResultMap">
     select * from t_mvc_book
  </select>
  <select id="list2" resultType="com.xieminglu.model.Book">
     select * from t_mvc_book
  </select>
  <select id="list3" resultType="com.xieminglu.model.Book" parameterType="com.xieminglu.model.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" parameterType="java.util.Map">
      select * from t_mvc_book where bid = #{bid}
  </select>
   @Test
    public void List() {
//        List<Book> books = this.bookService.list1();
//        List<Book> books = this.bookService.list2();
        List list=new ArrayList();
        list.add(1);
        list.add(12);
        list.add(16);
//        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));
    }

Paging query

Why rewrite the pagination of mybatis?
Mybatis's paging function is very weak. It is memory-based paging (find out all records and then get the result according to the offset offset and boundary limit). Such paging is basically useless in the case of large amounts of data.

Step by step using paging plug-in
1. Import pom dependency
2. Configure interceptor in Mybatis.cfg.xml
3. Use PageHelper for paging
4. Process paging results

Pom dependency

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

Mybatis.cfg.xml configuration interceptor

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

The order is according to the following picture, otherwise an error will be reported if the order is not correct.
Insert picture description here
Use PageHelper for paging
Mapper layer

List<Map> listPager(Map map);

Use paging plugin

 <select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
      select * from t_mvc_book where bname like #{bname}
  </select>

Service layer

 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.getTotal());
            System.out.println("当前页:" + pageInfo.getPageNum());
            System.out.println("页大小:" + pageInfo.getPageSize());
            pageBean.setTotal(pageInfo.getTotal()+"");
            System.out.println("总页数:" + pageBean.getMaxPage());
        }

        return list;
    }

Test code
Insert picture description here

Special character handling

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

Related code configuration

/*
    * mybatis特殊字符处理
    * */
    List<Book> list6(BookVo bookVo);
<select id="list6" resultType="com.xieminglu.model.Book" parameterType="com.xieminglu.model.BookVo">
       select * from t_mvc_book where price &gt; #{min} and price &lt; #{max}
  </select>
或
<select id="list6" resultType="com.xieminglu.model.Book" parameterType="com.xieminglu.model.BookVo">
      select * from t_mvc_book where <![CDATA[ price > #{min} and price < #{max} ]]>
  </select>

Insert picture description here

Guess you like

Origin blog.csdn.net/xieminglu/article/details/102594543