对于使用习惯了hibernate框架的朋友来说,级联查找一定是一个熟悉的名次,例如产品Product存储在仓库Warehouse中,那么每条产品记录都有一个指向仓库的外键值,我们根据Product的Id查找出该记录时会一并把warehouse记录也查找出来。
{
-
id: 1,
-
model: "Y450",
-
price: 4500,
-
productName: "联想笔记本",
-
remark: "好",
-
store: 120,
-
unit: "台",
-
warehouse: {
-
id: 2,
-
lastChangeTime: {
-
date: 18,
-
day: 4,
-
hours: 0,
-
minutes: 0,
-
month: 5,
-
seconds: 0,
-
time: 1434556800000,
-
timezoneOffset: -480,
-
year: 115
-
-
location: "杭州",
-
manager: "lee",
-
remark: "yes",
-
warehouseName: "第二号仓库"
-
然而在mybatis这个框架中,我们一开始却发现warehouse域变成了null。级联查询并没有发生,原因很简单,在配置Mapper.xml的时候,我们的写法是
<select id="findById" parameterType="Integer" resultType="Product">
select * from t_product where id=#{id}
</select>
resultType的写法使得复杂的POJO类不能作为一个属性被映射,只需要改成
<select id="findById" parameterType="Integer" resultMap="ProductResult">
select * from t_product where id=#{id}
</select>就可以了。
当然,在这之前应该配置ProductResult如下
<resultMap type="Product" id="ProductResult">
<result property="id" column="id"/>
<result property="productName" column="productName"/>
<result property="model" column="model"/>
<result property="unit" column="unit"/>
<result property="price" column="price"/>
<result property="store" column="store"/>
<result property="remark" column="remark"/>
<association property="warehouse" column="warehouse" select="com.java1234.dao.WarehouseDao.findById"></association>
</resultMap>