在MyBatis中,可以通过Collection映射来实现一对多关系。下面是一个示例,演示如何使用Collection映射实现一对多关系:
<!-- 定义父类实体 -->
<resultMap id="ParentMap" type="Parent">
<id property="id" column="parent_id" />
<result property="name" column="parent_name" />
<collection property="children" ofType="Child" resultMap="ChildMap" />
</resultMap>
<!-- 定义子类实体 -->
<resultMap id="ChildMap" type="Child">
<id property="id" column="child_id" />
<result property="name" column="child_name" />
</resultMap>
public interface ParentMapper {
@Select("SELECT parent_id, parent_name, child_id, child_name FROM parent_table JOIN child_table ON parent_table.parent_id = child_table.parent_id")
@Results({
@Result(property = "id", column = "parent_id"),
@Result(property = "name", column = "parent_name"),
@Result(property = "children", column = "{id=parent_id, name=parent_name}", javaType = List.class, many = @Many(select = "getChildByParentId"))
})
List<Parent> getAllParents();
@Select("SELECT child_id, child_name FROM child_table WHERE parent_id = #{id}")
List<Child> getChildByParentId(Integer id);
}
public class Parent {
private Integer id;
private String name;
private List<Child> children;
// getter and setter methods
}
public class Child {
private Integer id;
private String name;
// getter and setter methods
}
通过以上步骤,就可以通过MyBatis的Collection映射实现一对多关系了。在查询父实体时,会自动查询对应的子实体并封装到父实体的集合属性中。