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

本文介绍了Mybatis中一对多映射的实现,通过PropertyGroup和Property两个POJO类展示了如何建立关联关系。在Mapper文件中定义了resultMap,详细配置了一对多的集合属性,并利用foreach标签进行动态SQL查询,实现了根据属性ID列表获取属性组及其对应的多个属性的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值