第一种实现方式:
1)操作1:多对一的关系的操作,比如产品表与产品分类表。那么需要在产品表的数据里加入产品分类表的数据。产品表的实体类:Product,分类表的实体类:Cate
a.新建一个对象,这个对象是包含产品表的数据和产品分类的数据。这个对象的名字是ProductItem,它是继承自Product。
publicclass ProductItem extends Product {
public String getCateName() {
return cateName;
}
public void setCateName(StringcateName) {
this.cateName = cateName;
}
public String getCateDescription() {
return cateDescription;
}
public void setCateDescription(StringcateDescription) {
this.cateDescription =cateDescription;
}
private String cateName;
private String cateDescription;
}
b.创建相应的Mapper接口,比如叫ProductMapper接口。定义方式如下:
public interface ProductMapper {
public ProductItem getModel(int id);
}
C.创建ProductMapper.xml配置文件,配置文件格式如下:
<mappernamespace="com.gxa.bj.dao.ProductMapper">
<select id="getModel"resultType="com.gxa.bj.model.ProductItem">
Select p.*,c.name as cateName,
c.description as cateDescription
From Cate as c,Product p
Where c.id = p.cate_id
and p.id = #{id}
</select>
</mapper>
第二种实现方式:
多对一的关系的实现:在多的实体对象里包含一的实体对象
要求一个实体对象里必须包含另外的一个实体对象。比如说Product里必须包含的是Cate对象。
1)首先应该配置结果集(数据结果应该如何显示的)。配置的方式如下:
<!--配置结果集(查询的数据最终映射的对象的字段的关联)
type:表示同哪个实体对象进行映射的
id:表示这个结果的名字,后面如果要用到该结果集就会引用该名字
-->
<resultMaptype="com.gxa.bj.model.Product" id="productInfoResult">
<!-- 表示主键字段 -->
<id property="id"column="id" />
<!-- result就是形成一个映射关系,查询出的数据的字段映射成实体对象里的字段
property:表示的是实体对象的字段名字
column:表示的是查询出的数据的列名
-->
<result property="iprice"column="iprice"></result>
<result property="isHot"column="isHot"></result>
<result property="isShow"column="isShow"></result>
<result property="mprice"column="mprice"></result>
<result property="name"column="name"></result>
<result property="num"column="num"></result>
<result property="pubTime"column="pubTime"></result>
<result property="sn"column="sn"></result>
<result property="cate_id"column="cate_id"></result>
<!-- 关联另外一个实体对象 -->
<association property="cate"javaType="com.gxa.bj.model.Cate">
<!--为了保证列名不起冲,对应的列名起另外一个名字 -->
<id property="id"column="cateid"></id>
<resultproperty="description"column="description"></result>
<!--为了保证列名不起冲,对应的列名起另外一个名字 -->
<resultproperty="name" column="catename"></result>
</association>
</resultMap>
2)在接口中定义方法:
public interface ProductMapper {
public ProductItem getModel(int id);
public Product getProductModel(int id);
}
3)在ProductMapper.xml文件中实现的配置:
<!-- id名字对应到的接口的方法名,
resultMap:返回的结果映射应该对应到我们自己配置的映射集的名字。
-->
<select id="getProductModel"resultMap="productInfoResult">
Select p.*,c.id as cateid,c.name ascatename,
c.description
From Cate as c,Product p
Where c.id = p.cate_id
and p.id = #{id}
</select>