我有两个类:
class Apple {
Worm worm;
}
class Worm {
Apple apple;
}它们以1:1的方式存储在数据库中:
table Apple(id, wormId)
table Worm(id)每个苹果只有一个蠕虫,反之亦然。
使用out of iBatis,我可以简单地做到这一点:
Worm worm = new Worm();
Apple apple = new Apple();
worm.setApple(apple);
apple.setWorm(worm);我如何在ibatis中做到这一点?
<resultMap id="Apple" type="Apple">
<result property="id" column="id"/>
<result property="worm" column="id" select="getWormByApple"/>
</resultMap>
<resultMap id="Worm" type="Worm">
<result property="id" column="id"/>
<result property="apple" column="id" select="getAppleByWorm"/>
</resultMap>
<select id="getApple" resultMap="Apple" parameterClass="java.lang.Long">
SELECT * FROM Apples where id=#value#
</select>
<select id="getWormByApple" resultMap="Worm" parameterClass="java.lang.Long">
SELECT * FROM Worms where appleId=#value#
</select>所以,我希望能够做到:
Apple apple = foo.queryForObject("getApple", 42L);
Worm = worm.getApple();
Apple appleAgain = apple.getWorm().getApple();
// apple == appleAgain here相反,我得到的是StackOverFlowException,因为struts永远调用getWormByApple / getApple。
我在这里只看到一个解决方案:
class Apple {
void setWorm(Worm worm){
this.worm = worm;
worm.setApple(this);
}从蠕虫resultMap中删除“property=”苹果“”。
但这很糟糕,因为我必须记住哪些setter更新参数,而with不是。这也很糟糕,因为当蠕虫的setter改变参数时,可能会导致无限循环。
我也不想用我的模型类“修复”iBatis泄漏(也就是说,我根本不想接触我的模型bean)。
如果能有某种“后处理器”就好了:
<resultMap id="Apple" type="Apple">
<result property="id" column="id"/>
<result property="worm" select="getWormByApple"/>
<result property="worm.apple" postProcessor="appleToWormSetter"/>
</resultMap>但是在iBatis中没有。
我该怎么解决它呢?谢谢
发布于 2012-05-20 01:34:35
MyBatis自动求解循环引用。试试这个:
<select id="x" resultMap="appleResult">
select apple.id, worm.id from apple join worm on apple.worm_id = worm.id
</select>和两个类似这样的结果图:
<resultMap id="appleResult" type="Apple">
<id column="apple.id" property="id"/>
<association property="worm" resultMap="wormResult">
</resultMap>
<resultMap id="wormResult" type="Worm">
<id column="worm.id" property="id"/>
<association property="apple" resultMap="appleResult">
</resultMap>请注意,在这种情况下,MyBatis将检测循环并将两个对象链接在一起。
https://stackoverflow.com/questions/9588501
复制相似问题