温馨提示×

Result注解在MyBatis中实现一对一映射的技巧

小樊
97
2024-08-10 00:01:39
栏目: 编程语言

在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属性中。

0