The <choose> tag of mybatis is used

Records : 418

Scenario : Use the test attribute of the <when></when> tag of the <choose></choose> tag of MyBatis to make a non-null (!=null) or non-empty (!='') judgment on the value of the input attribute , or make equal (==) or unequal (!=) judgments with constants.

Versions : JDK 1.8, Spring Boot 2.6.3, mybatis-3.5.9.

1. Basic knowledge

1.1 MyBatis label

(1) View the tags supported by MyBatis

Address: http://mybatis.org/dtd/mybatis-3-mapper.dtd

(2) View label usage

Take the <mapper></mapper> tag element as an example, as follows in mybatis-3-mapper.dtd:

<!ELEMENT mapper (cache-ref | cache | resultMap* | parameterMap* | sql* | insert* | update* | delete* | select* )+>
<!ATTLIST mapper
namespace CDATA #IMPLIED
>

<!ELEMENT mapper(...)+>, indicating that this is a label element mapper.

(..|insert*|update* | delete* | select*), indicating the list of elements that can be nested in the mapper element.

<!ATTLIST mapper>, indicating that this is a supported attribute of an element tag.

1.2 Use of MyBatis

(1) Configure the location of the xml file mapped by mybatis in the application.yml configuration file.

mybatis:
  mapper-locations: classpath*:mapper/**/*.xml

(2) Create a Java interface. Add methods to the interface.

(3) Create a Java interface mapping xml file. Use the namespace attribute of the <mapper></mapper> tag in xml to specify the full path of the Java interface. The Java interface and the xml mapping file complete the binding relationship.

(4) In the <mapper></mapper> tag, use the id attribute of the tags such as <insert><update><delete><select> to specify the Java method name. The method of the Java interface and the tags inside the <mapper></mapper> of the xml mapping file complete the binding relationship.

2. Use the <choose> </choose> tag element

Scenario : The <choose></choose> tag element is used in tag elements such as <insert><update><delete><select>.

一般组合:<choose><when></when><otherwise></otherwise></choose>

一般组合:<choose><when></when><when></when></choose>

Example function : The example uses <choose></choose> tags to assemble SQL for different queries according to different conditions.

2.1 Java interface

@Repository
public interface Label02ChooseMapper {
  List<CityLabelPO> queryCity(CityLabelDTO cityLabelDTO);
}

2.2 XML file for Java interface mapping

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hub.example.mapper.Label02ChooseMapper">
  <select id="queryCity" parameterType="com.hub.example.domain.CityLabelDTO"
        resultType="com.hub.example.domain.CityLabelPO">
    select CITY_ID AS "cityId",
    <choose>
        <when test="flagColumn !=null and flagColumn !='' and flagColumn == '01' ">
            CITY_NAME AS "cityName",
            LAND_AREA AS "landArea",
            POPULATION AS "population",
            GROSS AS "gross",
            CITY_DESCRIBE AS "cityDescribe",
            DATA_YEAR AS "dataYear",
            UPDATE_TIME AS "updateTime"
        </when>
        <when test="flagColumn !=null and flagColumn !='' and flagColumn == '02' ">
            CITY_NAME AS "cityName",
            LAND_AREA AS "landArea"
        </when>
        <otherwise>
            CITY_NAME AS "cityName",
            LAND_AREA AS "landArea",
            POPULATION AS "population",
            GROSS AS "gross"
        </otherwise>
    </choose>
    from
    <choose>
        <when test="flagFrom !=null and flagFrom !='' and flagFrom == '01' ">
            t_city
        </when>
        <otherwise>
            t_city_01
        </otherwise>
    </choose>
    aa
    where
    <choose>
        <when test="cityId !=null and cityId !='' and flagWhere == '01' ">
            aa.CITY_ID = #{cityId}
        </when>
        <when test="cityName !=null and cityName !='' and flagWhere == '02' ">
            aa.CITY_NAME = #{cityName}
        </when>
    </choose>
  </select>
</mapper>

3. Test

3.1 Test code

@Slf4j
@RestController
@RequestMapping("/hub/example/cityLabel")
public class CityLabelController {
  @Autowired
  private Label02ChooseMapper label02ChooseMapper;
  @GetMapping("/load02")
  public Object load02() {
    log.info("测试开始...");
    // 示例一
    CityLabelDTO labelDTO = CityLabelDTO.builder()
            .cityId(1L).flagColumn("01")
            .flagFrom("01").flagWhere("01").build();
    List<CityLabelPO> labelPOList = label02ChooseMapper.queryCity(labelDTO);
    // 示例二
    labelDTO = CityLabelDTO.builder()
            .cityName("上海").flagColumn("02")
            .flagFrom("02").flagWhere("02").build();
    labelPOList = label02ChooseMapper.queryCity(labelDTO);
    log.info("测试结束...");
    return "执行成功";
  }
}

3.2 Test request

URL:http://127.0.0.1:18080/hub-example/hub/example/cityLabel/load02

3.3 Execute SQL

The example uses the <choose></choose> tag to assemble SQL for different queries according to different conditions to adapt to different business scenarios.

Example one:

SELECT
  CITY_ID AS "cityId",
  CITY_NAME AS "cityName",
  LAND_AREA AS "landArea",
  POPULATION AS "population",
  GROSS AS "gross",
  CITY_DESCRIBE AS "cityDescribe",
  DATA_YEAR AS "dataYear",
  UPDATE_TIME AS "updateTime"
FROM
  t_city aa
WHERE aa.CITY_ID = ?;

Example two:

SELECT
  CITY_ID AS "cityId",
  CITY_NAME AS "cityName",
  LAND_AREA AS "landArea"
FROM
  t_city_01 aa
WHERE aa.CITY_NAME = ?;

4. Support

4.1 Entity objects

(1) Encapsulate the result object CityLabelPO

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CityLabelPO {
  private Long cityId;
  private String cityName;
  private Double landArea;
  private Long population;
  private Double gross;
  private String cityDescribe;
  private String dataYear;
  private Date updateTime;
}

(2) Encapsulation parameter CityLabelDTO

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CityLabelDTO {
  private Long cityId;
  private String cityName;
  private Double landArea;
  private Long population;
  private Double gross;
  private String cityDescribe;
  private String dataYear;
  private Date updateTime;
  // 标记查询的字段
  private String flagColumn;
  // 标记查询的表
  private String flagFrom;
  // 标记where条件
  private String flagWhere;
}

4.2 Create table statement

CREATE TABLE t_city (
  CITY_ID BIGINT(16) NOT NULL COMMENT '唯一标识',
  CITY_NAME VARCHAR(64) COLLATE utf8_bin NOT NULL COMMENT '城市名',
  LAND_AREA DOUBLE DEFAULT NULL COMMENT '城市面积',
  POPULATION BIGINT(16) DEFAULT NULL COMMENT '城市人口',
  GROSS DOUBLE DEFAULT NULL COMMENT '生产总值',
  CITY_DESCRIBE VARCHAR(512) COLLATE utf8_bin DEFAULT NULL COMMENT '城市描述',
  DATA_YEAR VARCHAR(16) COLLATE utf8_bin DEFAULT NULL COMMENT '数据年份',
  UPDATE_TIME DATETIME DEFAULT NULL COMMENT '更新时间'
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='城市信息表';

Above, thanks.

April 23, 2023

Guess you like

Origin blog.csdn.net/zhangbeizhen18/article/details/130330879