温馨提示×

如何通过MyBatis的Collection映射实现一对多关系

小樊
104
2024-08-09 22:49:38
栏目: 编程语言

在MyBatis中,可以通过Collection映射来实现一对多关系。下面是一个示例,演示如何使用Collection映射实现一对多关系:

  1. 首先,在Mapper XML文件中定义两个实体类和对应的映射关系:
<!-- 定义父类实体 -->
<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>
  1. 接着,在Mapper接口中定义查询方法,使用Collection映射来获取一对多关系:
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);
}
  1. 最后,在实体类中定义父类和子类的属性以及对应的getter和setter方法:
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映射实现一对多关系了。在查询父实体时,会自动查询对应的子实体并封装到父实体的集合属性中。

0