Mybatis uses annotation to implement dynamic sql

In the development process, many businesses need to dynamically generate sql to complete. For example, when the front end displays an item, the items need to be paged and sorted. This requires at least four parameters to be passed in, which page, page size, sort field, ascending or descending order. Dynamically generate sql based on these four parameters. Mybatis provides a way to manage SQL statements using xml and annotation. Here is the way to use annotation, because annotation is more object-oriented.
There are two ways to dynamically generate sql in annotation.


  1. This method is not recommended for splicing sq in annotation , because this method is much different from xml and requires other tags, which seriously affects the readability of the code. For example, the dynamic SQL that implements paging query is as follows:
 @Select({
    
    "<script>" ,
            "select name,price,num from bin_info.goods ",
            "<if test='sortField!=null'> order by #{sortField} </if>",
            "<if test='pageNumber!='' and pageSize!='''> limit #{pageNumber} offset #{pageSize} </if>",
            "</script>"})
    List<Goods> findGoods(PageDto dto);

  1. The way to refer to the provider in the annotation is more similar. A provider class needs to be introduced. The provider mainly completes the dynamic splicing of SQL, and then references the corresponding SQL in the mapper layer through reflection. The logic in 1 is implemented as follows:
    First, Create a provider for splicing dynamic SQL:

import com.channing.dto.PageDto;
import org.apache.ibatis.jdbc.SQL;

import java.util.Map;

/**
 * @author :channing
 * @date :Created in 5/12/2020 6:03 PM
 * @description:${The sql provider for goods}
 */
public class GoodsSqlProvider {
    
    
    public String findByPage(Map<String,PageDto> param){
    
    
        PageDto pageDto = param.get("page_dto");
        String pageString = new SQL(){
    
    
            {
    
    //notice: here used code block, if don't use,the following sql FUNCTION can not be used.
                SELECT("name,price,num");
                FROM("bin_info.goods");
                String sortField = pageDto.getSortField();
                if(sortField!=null) ORDER_BY(sortField);
                if(pageDto.getPageNumber()!=null && pageDto.getPageSize()!=null) {
    
    
                    LIMIT(pageDto.getPageNumber().intValue());
                    OFFSET(pageDto.getPageSize().intValue());
                }
            }
        }.toString();

        return pageString;


    }
}

Second, define the interface in the mapper:

@SelectProvider(method = "findByPage",type=GoodsSqlProvider.class)
    List<Goods> findGoods(@Param("page_dto")PageDto dto);

The PageDto used in this article is as follows. The Long type is used because it can be set to null. When it is null, the corresponding parameter does not need to be spelled into sql. If long is used, paging must be performed each time.


import lombok.Data;

/**
 * @author :channing
 * @date :Created in 5/12/2020 5:09 PM
 * @description:${The page Dto contains four 4 parameters, dynamic sql will be based on them.}
 */
@Data
public class PageDto {
    
    
    private Long pageNumber;
    private Long pageSize;
    private String sortField;
    private String sortOrder;
}

Note: Postgresql is used in this article

Guess you like

Origin blog.csdn.net/hongyinanhai00/article/details/106086325