一,关联查询(一对一)
association属性可以配置映射关联查询单个对象的映射信息
例子:(我们这里直接用多对一代替一对一,原理相同)一个商品goods只能有一个类型Types,一个类型可以有多个商品
☆思路:使用resultMap将查询结果中的商品信息映射到Goods对象中,在Goods类中添加Types属性,将关联查询出来的类型信息映射到Goods对象中的types属性中。
1,实体类
Goods:(里面有类型Types的)
public class Goods implements Serializable{
private Integer id;
private String goodsname;
private String godsfullname;
private Integer num;
private Integer typeid;
private Types types;
public Types getTypes() {
return types;
}
public void setTypes(Types types) {
this.types = types;
}
public Goods() {
super();
}
public Goods(Integer id, String goodsname, String godsfullname, Integer num, Integer typeid) {
this.id = id;
this.goodsname = goodsname;
this.godsfullname = godsfullname;
this.num = num;
this.typeid = typeid;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGoodsname() {
return goodsname;
}
public void setGoodsname(String goodsname) {
this.goodsname = goodsname;
}
public String getGodsfullname() {
return godsfullname;
}
public void setGodsfullname(String godsfullname) {
this.godsfullname = godsfullname;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getTypeid() {
return typeid;
}
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
}
Types:
package com.study.bean;
import java.io.Serializable;
public class Types implements Serializable{
private int id;
private String name;
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;
}
}
2,mapper接口和mapper.xml文件
mapper:
// 一对一查询
public List<Goods> selectGoodsAndTypes();
mapper.xml:
<!--一对一关系resultMap
extends:可以继承其他的resultMap
-->
<resultMap id="selectGoodsAndTypes" type="Goods">
<!---->
<id column="id" property="id"></id>
<result column="goodsname" property="goodsname"></result>
<result column="godsfullname" property="godsfullname"></result>