[JAVA] correspondence between mybatis table column name and field name

Premise

I will explain the mechanism (mapping) that associates the table column name with the field name used in the code in MyBatis.

There are four types of mapping methods. In the field, you will choose one of them.

  1. Use the standard automatic mapping function
  2. Correspond to each one in AS clause
  3. Turn on the camel case automatic mapping function
  4. Manage with resultMap tag

1. Use the standard automatic mapping function

The standard setting of MyBatis is "Ignore the difference between lowercase and uppercase letters and associate them".

The following examples are automatically associated and operate.

Example: (table column name) A_COLUMN → (field name) a_column or a_Column

2. Correspond one by one with the as clause

When writing an SQL statement, describe the correspondence in the AS clause.

SQL statement


SELECT
    A_COLUMN AS "aColumn",
    B_COLUMN AS "bColumn",
FROM
    MY_TABLE
WHERE
    A_COLUMN = "test"

Field name


Public Class myTableDto {
    String aColumn;
    String bColumn;
}

3. Turn on the camel case automatic mapping function

In the config file (eg mybatis-config.xml)

mybatis-config.xml


<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

If you specify, the column name with underscore will automatically correspond to camel case (capitalize the beginning of the second word).

Example: (table column name) ADD_COLUMN → (field name) @Column

4. Manage with resultMap tag

In the Mapper file called from the config file, use the resultMap tag to describe the correspondence.

testMapper.xml


<mapper namespace="org.apache.ibatis.example.Mapper">
    <resultMap type="org.apache.ibatis.example.dto.myTableDto" id="testmap">
        <result column="A_COLUMN" property="aColumn"/>
        <result column="B_COLUMN" property="bColumn"/>
    </resultMap>
    
    <select id="getAll" resultMap="testmap">
        SELECT * FROM MY_TABLE
    </select>
</mapper>

Miscellaneous feelings

Personally, I might like to write in the AS clause, which makes it easy to see if there are any omissions when looking at the SQL statement.

Recommended Posts

correspondence between mybatis table column name and field name
Basic CRUD comparison between Mybatis and Hibernate
Various correspondence table of Spring Framework and Spring Boot
[Rails] How to change the column name of the table
Since Activator is welcoming EOL, we will create a correspondence table between Activator and SBT commands.