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

avatar
作者
筋斗云
阅读量:0

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!