- 一对一关系映射:
@Results(id = "UserResultMap", value = {
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "address", column = "address"),
@Result(property = "contact", column = "contact_id",
one = @One(select = "com.example.mapper.ContactMapper.getContactById"))
})
@Select("SELECT * FROM user")
public List<User> getUserList();
在上述示例中,@Results 注解定义了一个名为 "UserResultMap" 的 ResultMap,并通过 @Result 注解指定了实体类属性与查询结果集字段的映射关系。其中,one = @One 表示进行一对一关系的映射配置,并通过 select 属性指定了关联表的查询。
- 一对多关系映射:
@Results(id = "UserResultMap", value = {
// 省略一对一关系的映射配置
@Result(property = "orders", column = "id",
many = @Many(select = "com.example.mapper.OrderMapper.getOrdersByUserId"))
})
@Select("SELECT * FROM user")
public List<User> getUserList();
在这个示例中,@Results 注解中通过 @Result 注解进行映射关系配置,其中 many = @Many 表示进行一对多的映射配置,并通过 select 属性指定了关联表的查询。
- 多对多关系映射:
@Results(id = "StudentResultMap", value = {
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "courses", column = "id",
many = @Many(select = "com.example.mapper.CourseMapper.getCoursesByStudentId"))
})
@Select("SELECT * FROM student")
public List<Student> getStudentList();
在上述示例中,@Results 注解中的 @Result 注解定义了实体类属性与查询结果集字段的映射关系,其中 many = @Many 表示进行多对多的映射配置,并通过 select 属性指定了关联表的查询。
- 自定义映射逻辑:
@Results(id = "UserResultMap", value = {
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age", javaType = Integer.class, jdbcType = JdbcType.INTEGER,
typeHandler = CustomAgeTypeHandler.class)
})
@Select("SELECT * FROM user")
public List<User> getUserList();
在这个示例中,@Results 注解中的 @Result 注解中通过 typeHandler 属性指定了自定义的类型处理器 CustomAgeTypeHandler,用于处理查询结果集中的 age 字段并转换为实体类的 age 属性。