最近在写项目的时候有一个寄件管理的功能,里面要读物品表中的信息,并根据物品id从订单表中找到对应订单一起把数据输出出来,这样就用到了MyBatis中的关联映射,因为做的时候不记得了所以特地复习了一下,记录一下过程。
首先确保物品表中的id是订单表中的外键或主键,通过物品id可以找到订单。
然后建对应数据库属性的对象vo文件,Bill.java
public class Bill {
private int trackingID;
private int giveUserID;
private int acceptUserID;
private String sendaddress;
private String arriveaddress;
private String trainnumber;
private int complete;
private float cost;
}
Goods.java
public class Goods {
private int trackingID;
private float weight;
private String type;
private String name;
private Bill bill;
}
需要注意的是因为是关联映射,所以goods类里面需要有bill对象,这样才能把搜到的对应订单保存起来。
然后在mapper.xml文件中加mysql映射
<select id="selectBill" resultType="bill" parameterType="int">
select * from bill where trackingID=#{trackingID}
</select>
<select id="goodsManage" resultMap="goodsResult">
select * from goods_info
</select>
<resultMap type="goods" id="goodsResult">
<id property="trackingID" column="trackingID"/>
<result property="weight" column="weight"/>
<result property="type" column="type"/>
<result property="name" column="name"/>
<association property="bill" column="trackingID" select="selectBill" javaType="bill"></association>
</resultMap>
</mapper>
id为映射语句的唯一标识符,resultType为返回类型,parameterType为参数类型,resultMap是在数据库表与vo类属性不对应时使用的,关联映射时就会用到,select中的resultMap属性找到对应id值的resultMap返回结果集,结果集的字段时自己设置的,type="goods"意味着返回goods的类型,id为主键,result为普通属性,property为vo中的属性,column是数据库表中的属性,写完数据库中goods表的属性后通过association关联到订单表,select使得association找到id为selectBill的映射语句也就是上面那个,将trackingID作为参数,设置javaType返回bill型,这样就存在了goods类里面的bill属性中。
一开始写的时候页面跳转错误,后来发现是< mapper namespace=“com.?.ssm.dao.AdminMapper”>与select="com.?.ssm.dao.AdminMapper.selectBill"重复了,因为在命名空间中找不到再加com.?.ssm前缀的的函数,去掉就好。
然后mapper接口加上
public Bill selectBill(int trackingID);
public List<Goods> goodsManage();
Service中加上
//根据商品id搜查商品
@Transactional
public Bill selectBill(int id){
return adminMapper.selectBill(id);
}
//寄件管理陈列
@Transactional
public List<Goods> goodsManage(){
return adminMapper.goodsManage();
}
controller中调用Service.goodsManage()就可以得到联表查询的list类型数据了。然后在前端jstl调用时注意bill里面的值写成${goods.bill.cost}就好。