The <resultMap> tag of mybatis is used

Records : 420

Scenario : Use MyBatis's <resultMap></resultMap> to manually specify the query result object properties, types and database table field properties and types in one-to-one correspondence. Use the properties property, javaType, jdbcType, column of <result></result> to complete the corresponding relationship. Use the resultMap attribute reference of tags such as <select>.

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 <resultMap></resultMap> tag element

Scenario : The <resultMap></resultMap> tag element is defined in <mapper></mapper>. Use the resultMap attribute reference in tag elements such as <insert><update><delete><select>.

2.1 Java interface

@Repository
public interface Label05ResultMapMapper {
  List<CityLabelPO> queryCity01(CityLabelPO cityPO);
  List<CityLabelPO> queryCity02(CityLabelPO cityPO);
}

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.Label05ResultMapMapper">
  <resultMap id="poResult" type="com.hub.example.domain.CityLabelPO">
      <result property="cityId" javaType="java.lang.Long" jdbcType="BIGINT" column="CITY_ID"></result>
      <result property="cityName" javaType="java.lang.String" jdbcType="VARCHAR" column="CITY_NAME"></result>
      <result property="landArea" javaType="java.lang.Double" jdbcType="DOUBLE" column="LAND_AREA"></result>
      <result property="population" javaType="java.lang.Long" jdbcType="BIGINT" column="POPULATION"></result>
      <result property="gross" javaType="java.lang.Double" jdbcType="DOUBLE" column="GROSS"></result>
      <result property="cityDescribe" javaType="java.lang.String" jdbcType="VARCHAR" column="CITY_DESCRIBE"></result>
      <result property="dataYear" javaType="java.lang.String" jdbcType="VARCHAR" column="DATA_YEAR"></result>
      <result property="updateTime" javaType="java.util.Date" jdbcType="TIMESTAMP" column="UPDATE_TIME"></result>
  </resultMap>
  <!-- 1.使用resultMap标签封装返回结果对象-->
  <select id="queryCity01" resultMap="poResult">
      select aa.*
      from t_city aa
      where aa.CITY_ID = #{cityId}
  </select>
  <!-- 2.使用resultType属性指定封装结果对象,以及每个属性执行封装属性名称-->
  <select id="queryCity02" resultType="com.hub.example.domain.CityLabelPO">
      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 = #{cityId}
  </select>
</mapper>

2.3 Use resultMap type matching

When using <resultMap></resultMap>, you need to manually match attributes and classes.

(1) Types in the database, you can use the following SQL query

In MySQL:

SELECT
  aa.column_name,
  aa.data_type
FROM
  INFORMATION_SCHEMA.COLUMNS aa
WHERE aa.TABLE_NAME = 't_city'
在Oracle中:
SELECT
  aa.COLUMN_NAME,
  aa.DATA_TYPE
FROM
  user_tab_columns aa
WHERE aa.table_name = 'T_CITY'

In Oracle:

SELECT
  aa.COLUMN_NAME,
  aa.DATA_TYPE
FROM
  user_tab_columns aa
WHERE aa.table_name = 'T_CITY'

(2) Type in MyBatis

Type in MyBatis: org.apache.ibatis.type.JdbcType.

public enum JdbcType {
    ARRAY(2003),
    BIT(-7),
    TINYINT(-6),
    SMALLINT(5),
    INTEGER(4),
    BIGINT(-5),
    FLOAT(6),
    REAL(7),
    DOUBLE(8),
    NUMERIC(2),
    DECIMAL(3),
    CHAR(1),
    VARCHAR(12),
    LONGVARCHAR(-1),
    DATE(91),
    TIME(92),
    TIMESTAMP(93),
    BINARY(-2),
    VARBINARY(-3),
    LONGVARBINARY(-4),
    NULL(0),
    OTHER(1111),
    BLOB(2004),
    CLOB(2005),
    BOOLEAN(16),
    CURSOR(-10),
    UNDEFINED(-2147482648),
    NVARCHAR(-9),
    NCHAR(-15),
    NCLOB(2011),
    STRUCT(2002),
    JAVA_OBJECT(2000),
    DISTINCT(2001),
    REF(2006),
    DATALINK(70),
    ROWID(-8),
    LONGNVARCHAR(-16),
    SQLXML(2009),
    DATETIMEOFFSET(-155),
    TIME_WITH_TIMEZONE(2013),
    TIMESTAMP_WITH_TIMEZONE(2014);
    public final int TYPE_CODE;
    private static Map<Integer, JdbcType> codeLookup = new HashMap();
    private JdbcType(int code) {
        this.TYPE_CODE = code;
    }
    public static JdbcType forCode(int code) {
        return (JdbcType)codeLookup.get(code);
    }
    static {
        JdbcType[] var0 = values();
        int var1 = var0.length;
        for(int var2 = 0; var2 < var1; ++var2) {
            JdbcType type = var0[var2];
            codeLookup.put(type.TYPE_CODE, type);
        }
    }
}

(3) Types in Java entity classes

The type in the Java entity class is directly viewed in the definition object. for example:

java.lang.Integer
java.lang.Long
java.lang.Double
java.lang.String
java.lang.String
java.util.Date
java.lang.Boolean

3. Test

3.1 Test code

@Slf4j
@RestController
@RequestMapping("/hub/example/cityLabel")
public class CityLabelController {
  @Autowired
  private Label05ResultMapMapper label05ResultMapMapper;
  @GetMapping("/load05")
  public Object load05() {
    log.info("测试开始...");
    CityLabelPO cityPO = CityLabelPO.builder().cityId(3L).build();
    // 示例一 
    List<CityLabelPO> list01 = label05ResultMapMapper.queryCity01(cityPO);
    // 示例二 
    List<CityLabelPO> list02 = label05ResultMapMapper.queryCity02(cityPO);
    log.info("测试结束...");
    return "执行成功";
  }
}

3.2 Test request

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

3.3 Execute SQL

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

Example one:

select aa.* from t_city aa where aa.CITY_ID = ?

Example two:

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 = ?

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

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/130331263