Mybatis 一对多映射 collection 和foreach的使用

1、表的关联关系
属性组表(组ID、组名称) --- 一的一方
属性表(属性ID、组ID、属性名称) --- 多的一方

2、定义POJO类
属性组
public class PropertyGroup {
private String groupId;
private String groupName;
private List<Property> propertyIds; //一个属性组有多个属性
..省略了getter和setter方法
}
属性
public class Property {
private String propertyId;
private String groupId;
private String propertyName;
...省略了getter和setter方法
}

3、定义Dao接口方法
List<PropertyGroup> getResults(List<String> propertyIds);
4、定义Mapper文件
<!--一对多测试例子 -->
A、定义结果集
<resultMap id="PropertyGroupResult" type="com.example.entity.PropertyGroup">
<id column="group_id" property="groupId"></id>
<result column="group_name" property="groupName"></result>
<collection property="propertyIds" ofType="com.example.entity.Property">
<id column="property_id" property="propertyId"></id>
<result column="property_name" property="propertyName"></result>
</collection>
</resultMap>
B、定义SQL查询语句
<select id="getResults" parameterType="java.util.List" resultMap="PropertyGroupResult">
select pg.group_id,pg.group_name,p.property_id,p.property_name from property p left join property_group pg
on p.group_id = pg.group_id where p.property_id in
<foreach collection="list" item="propertyId" index="index" open="(" close=")" separator=",">
#{propertyId}
</foreach>
</select>


猜你喜欢

转载自blog.csdn.net/lichuangcsdn/article/details/80862125