在MyBatis中,可以使用Result注解來實現一對一映射。以下是一個示例:
首先,創建兩個實體類,一個是主實體類,一個是關聯實體類。
public class User {
private Long id;
private String username;
private Profile profile;
// getters and setters
}
public class Profile {
private Long id;
private String email;
private String phone;
// getters and setters
}
然后,在Mapper接口中定義查詢方法,使用Result注解來映射一對一關系:
public interface UserMapper {
@Select("SELECT u.id, u.username, p.id as profile_id, p.email, p.phone FROM user u " +
"LEFT JOIN profile p ON u.id = p.user_id WHERE u.id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "profile.id", column = "profile_id"),
@Result(property = "profile.email", column = "email"),
@Result(property = "profile.phone", column = "phone")
})
User getUserById(Long id);
}
最后,在配置文件中配置Mapper接口和對應的SQL語句:
<configuration>
<mappers>
<mapper class="com.example.UserMapper"/>
</mappers>
</configuration>
通過以上步驟,就可以實現一對一映射的查詢操作。在查詢User時,會自動查詢出對應的Profile信息,并將其映射到User實體類的profile屬性中。