MyBatis One-to-One Mapping Guide

In MyBatis, implementing a one-to-one mapping relationship can be achieved by defining the mapping in the MyBatis mapper file using tags. Here is an example:

  1. Create two entity classes, one being the main entity class and the other being the associated entity class.
public class MainEntity {
    private Long id;
    private String name;
    private SubEntity subEntity;
    
    // getters and setters
}

public class SubEntity {
    private Long id;
    private String subName;
    
    // getters and setters
}
  1. Create a corresponding mapper file and define a resultMap to achieve a one-to-one mapping relationship.
<!-- MainEntityMapper.xml -->
<mapper namespace="com.example.MainEntityMapper">
    
    <resultMap id="MainEntityResultMap" type="com.example.MainEntity">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        
        <association property="subEntity" column="sub_id" javaType="com.example.SubEntity">
            <id property="id" column="sub_id"/>
            <result property="subName" column="sub_name"/>
        </association>
    </resultMap>
    
    <select id="selectMainEntityById" resultMap="MainEntityResultMap">
        SELECT
            m.id,
            m.name,
            s.id as sub_id,
            s.sub_name
        FROM
            main_entity m
        LEFT JOIN
            sub_entity s
        ON
            m.sub_id = s.id
        WHERE
            m.id = #{id}
    </select>
</mapper>
  1. Define a query method in the corresponding Java interface.
public interface MainEntityMapper {
    MainEntity selectMainEntityById(Long id);
}
  1. Configure the corresponding mapper in the MyBatis configuration file.
<!-- mybatis-config.xml -->
<configuration>
    <mappers>
        <mapper resource="com/example/MainEntityMapper.xml"/>
    </mappers>
</configuration>
  1. Invoke the query method in the code to retrieve a one-to-one mapping relationship.
MainEntity mainEntity = mainEntityMapper.selectMainEntityById(1L);
System.out.println(mainEntity.getName());
System.out.println(mainEntity.getSubEntity().getSubName());

By following the above steps, the operation of querying a one-to-one mapping relationship can be achieved.

bannerAds