关于多对多关系,我看了很多网上的案例和讲解,觉得都说的不太清楚,决定自己结合之前学的hibernate多对多关系,自己写一篇有关的mybatis多对多关系总结。
打印一下,记录
分别为三张表,一张银行用户表,简单起见,只有id和name两列,一张银行卡表,有id和money两列,最后是一张关系维护表,有三列,id、对应用户的buserid、对应卡的bcardid。
我设定的银行卡为家庭卡,可以多个人用一个账号,一个人可以用多张卡。
package com.test.domain;
import java.util.List;
public class Buser {
private int id;
private String name;
private List<Bcard> bcards;
public List<Bcard> getBcards() {
return bcards;
}
public void setBcards(List<Bcard> bcards) {
this.bcards = bcards;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
创建并配置对应的mapper映射文件
<mapper namespace="com.test.mapper.BuserMapper">
<resultMap type="buser" id="resultUmap">
<id column="id" property="id" />
<result column="name" property="name"/>
<!-- <collection property="uList" ofType="com.test.domain.Ctou">
<id column="c_id" property="id" />
<result column="buserid" property="buserid" />
<result column="bcardid" property="bcardid" />
</collection> -->
<collection property="bcards" ofType="com.test.domain.Bcard">
<id column="b_id" property="id" />
<result column="money" property="money" />
</collection>
</resultMap>
<select id="selectMtoM" parameterType="java.lang.Integer" resultMap="resultUmap">
SELECT buser.*,bcard.id b_id,bcard.money from buser,ctou,bcard
where buser.id=#{value} and buser.id=ctou.buserid and ctou.bcardid=bcard.id
</select>
</mapper>
public interface BuserMapper {
public Buser selectMtoM(Integer value) throws Exception;
}
记得在总配置文件里配置
<typeAliases>
<package name="com.me.domain"/>
<package name="com.test.domain"/>
</typeAliases>
<mappers>
<!-- <mapper resource="sqlmap/User.xml"/> -->
<package name="com.me.mapper"/>
<package name="com.test.mapper"/>
</mappers>
测试
Buser buser=buserMapper.selectMtoM(111);
System.out.println(buser.getName());
for (Bcard bcard : buser.getBcards()) {
System.out.println(bcard.getId()+" "+bcard.getMoney());
}
反过来从bcard来查buser也一样的步骤。
over~