[英]Mapping a tree with MyBatis?
I'm trying to muddle my way thru setting up a tree structure and mapping it with MyBatis. 我试图通过设置树结构并使用MyBatis映射它来弄乱自己的方式。 My table is defined as;
我的表定义为;
CREATE TABLE `Hierarchy` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parentId` int(11) NULL DEFAULT NULL,
`name` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I tried to do an association in MyBatis with; 我试图与MyBatis建立关联;
@Select(SELECT_ALL)
@Results(value = {
@Result(property = "id", column = "id"),
@Result(property = "children", column = "parentId",
jdbcType = JdbcType.NUMERIC,
many = @Many(select = "selectById")),
@Result(property = "name", column = "name")
})
List<Hierarchy> selectAll();
My class has; 我班有
private Integer id;
private Integer parentId;
private String name;
private List<Hierarchy> children;
I pretty quickly realized this wouldn't work, since it's going to wind up associating backwards, and I get children back multiple times in the result set. 我很快意识到这是行不通的,因为它最终将向后关联,并且我在结果集中多次返回了孩子。 So what's the answer?
那么答案是什么呢? Do I have to iterate after I do the select and populate my children that way?
完成选择并以这种方式填充我的孩子后,是否需要迭代?
I tried a few approaches to that, but they all seem horribly inefficient, and I'm finding it hard to handle forward-references of parent id's without iterating the list twice. 我尝试了几种方法,但是它们似乎都效率极低,而且我发现很难处理父ID的前向引用而又不会重复两次该列表。
So, has anyone pulled this off before? 那么,有没有人把它拉下来? What's the trick?
诀窍是什么?
I did this a few years ago with iBatis, and was never satisfied with the result. 几年前,我使用iBatis做到了这一点,但对结果从未满意。 My tree was read-only, which simplified the code.
我的树是只读的,这简化了代码。 I also needed to navigate the tree up and down, so each record had a parent class pointer.
我还需要上下导航树,因此每个记录都有一个父类指针。 The algorithm (using your class names etc) was:
该算法(使用您的类名等)为:
This all works fine but is far from elegant. 这一切都很好,但远非优雅。 As you noted, it needs two passes through the list.
如您所述,该列表需要两次通过。 If you find a better method, please share it.
如果您找到更好的方法,请分享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.