Hibernate AliasToBean 与集合
我在父类和子类之间定义了双向一对多关系。我希望执行一个查询,以便可以在 bean 中返回单个父级及其子级的子集。
public class Parent {
private int id;
private Set<Child> children = new HashSet<Child>(0);
// other fields + getters and setters
}
public class Child {
private Parent parent;
private int age;
// other fields + getters and setters
}
我希望实现的输出是:
public class ParentChildWrapper {
private Parent parent;
private Collection<Child> children; // subset of children
}
我想过滤父母的 ID 和孩子的年龄列。我尝试了多种查询组合以获得所需的输出。
以下内容很接近,但没有将子项分组到我定义的 ParentChildWrapper bean 的集合中。我得到的结果是一个对象列表,每个子对象有 1 个实例与年龄过滤器匹配:
Query q = session.createQuery(
"SELECT p, c " +
"FROM Parent p " +
"INNER JOIN p.children c " +
"WHERE p.id = :id " +
"AND c.age = :age"
);
我还尝试按父对象进行分组,以便尝试将所有子对象聚合到一个集合中,但也无济于事。
显然,我可以将其分为两个单独的查询,以便选择父级,然后选择我想要的子级。但感觉这应该是一个相当常见的用例。也许我没有以冬眠式的方式思考。
I have a bi-directional one-to-many relationship defined between Parent and Child classes. I'm looking to execute a query such that I can return a single parent, and a subset of its children in a bean.
public class Parent {
private int id;
private Set<Child> children = new HashSet<Child>(0);
// other fields + getters and setters
}
public class Child {
private Parent parent;
private int age;
// other fields + getters and setters
}
The output I'm looking to achieve is:
public class ParentChildWrapper {
private Parent parent;
private Collection<Child> children; // subset of children
}
I'd like to filter on the parent's id and the child's age column. I've tried a number of query combinations in order to get the desired output.
The following is close, but doesn't group the children in a collection in the ParentChildWrapper bean I've defined. The result I get is a list of objects, with 1 instance per child that matches the age filter:
Query q = session.createQuery(
"SELECT p, c " +
"FROM Parent p " +
"INNER JOIN p.children c " +
"WHERE p.id = :id " +
"AND c.age = :age"
);
I've also tried to group by the parent in order to try and aggregate all the children into a collection, also to no avail.
Obviously I could separate this into two separate queries in order to select the parent, and then select the children that I want. But it feels like this should be a fairly common use case. Perhaps I'm not thinking in a hibernate-esque way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是不要使用任何转换器并自己编写循环代码:
这会生成 8 行简单代码,而不是 1 行,但避免了反射调用,从而允许安全重构。
Just don't use any transformer and code the loop yourself:
This makes 8 lines of trivial code instead of 1, but avoids reflection calls, and thus allows safe refactoring.