在MyBatis中实现一对一映射关系可以通过在MyBatis的mapper文件中使用
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
}
<!-- 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>
public interface MainEntityMapper {
MainEntity selectMainEntityById(Long id);
}
<!-- mybatis-config.xml -->
<configuration>
<mappers>
<mapper resource="com/example/MainEntityMapper.xml"/>
</mappers>
</configuration>
MainEntity mainEntity = mainEntityMapper.selectMainEntityById(1L);
System.out.println(mainEntity.getName());
System.out.println(mainEntity.getSubEntity().getSubName());
通过以上步骤,就可以实现一对一映射关系的查询操作。