14、查询注入
查询注入是在一个查询中嵌入另外一个查询,这样做的目的是为了实现实体对象之间的关联关联关系(一对一、一对多、多对多)分单项双向。有关这些内容,是比较复杂的,笔者对此做了深入研究,并分别写了三篇来讲述。
查询注入的实现就是在实体属性为另外一个实体或者实体集合的时候,引入一个相关的查询来实现,例如,客户和订单的映射关系:
public class Customer {
private Long id;
private String name;
private String address;
private String postcode;
private String sex;
private Long id;
private String name;
private String address;
private String postcode;
private String sex;
private List<Orders> orderlist = new ArrayList<Orders>();
}
<resultMap id="result" class="customer">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="address" column="address"/>
<result property="postcode" column="postcode"/>
<result property="sex" column="sex"/>
<result property="orderlist" column="id" select="orders.findByCustomerId"/>
</resultMap>
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="address" column="address"/>
<result property="postcode" column="postcode"/>
<result property="sex" column="sex"/>
<result property="orderlist" column="id" select="orders.findByCustomerId"/>
</resultMap>
在这个映射中,为了查询客户的时候,能查询到相关的订单,可以在映射
orderlist属性的时候,将其指向另外一个查询
orders.findByCustomerId,这个查询是以Customer的
id为参数来查询的。
select="orders.findByCustomerId"这个查询定义如下:
<select id="findByCustomerId" resultMap="result_base" parameterClass="long">
select * from orders where customerId = #value#
</select>
select * from orders where customerId = #value#
</select>
原理就是这么简单,然后根据实际情况,可以自由实现实体间的关联关系。