gpt4 book ai didi

java - 具有列表 getter 的 Hibernate HQL

转载 作者:太空宇宙 更新时间:2023-11-04 09:00:58 24 4
gpt4 key购买 nike

我有一个 Hibernate 实体,带有映射为 @OneToMany 的 getter:

@Entity
class Parent extends BaseParent {

@OneToMany(cascade = {CascadeType.ALL}, mappedBy = "parent")
public List<Child> getChildren() {
return super.children;
}

public void setChildren(List<Child> list) {
super.children = list;
}
}

当我尝试执行一些 HQL 时,例如:

select p 
from Parent p
left join p.children c
where c.name='foobar'

我收到以下异常:

org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: children of: ....Parent

如果我将 @OneToMany 注释放在 protected 字段上,则查询将有效。我怎样才能让它工作,以便可以将注释放在 getter 上?

最佳答案

您可能会遇到与注释中字段和方法混合相关的问题。例如,如果您的父类 BaseParent 中有 @Id 注释,那么 Hibernate 将默认查看字段而不是方法。

所以基本上如果你有这样的事情:

public class BaseParent {
@Id
private Integer id;

protected List<Child> children;
}

public class Parent extends BaseParent {
@ManyToOne
public List<Child> getChildren() {super.getChildren();}
}

Hibernate 在确定 @ManyToOne 注释时会遇到问题。另外,这可能可以解释为什么将注释添加到父类中的字段使其起作用。

在上面提到的同一页面( http://docs.jboss.org/ejb3/app-server/HibernateAnnotations/reference/en/html_single/index.html#d0e253 ),还有这样一段:

Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property. The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of @Id or @EmbeddedId.

因此,为了让它发挥作用,您可能需要选择其中之一(字段与方法)并保持一致。这样,您就不会遇到这些“奇怪的” hibernate 问题。

无论如何,希望对您有所帮助。

关于java - 具有列表 getter 的 Hibernate HQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/518267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com