在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映射實現一對多關系了。在查詢父實體時,會自動查詢對應的子實體并封裝到父實體的集合屬性中。