java Hibernate额外懒惰不工作
我有两个实体: 条目和注释。一个条目有n条注释。 我想在我的评论条目中添加额外的延迟加载。我的实体看起来像:
@Entity
@Table(name="entries")
public class Entry {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@OneToMany(mappedBy = "entry", cascade = CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.EXTRA)
private List<Comment> comments = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Comment> getComments() {
return comments;
}
public boolean containsComment(int commentId) {
return comments.contains(commentId);
}
public Comment getComment(int commentId) {
return comments.get(commentId);
}
}
@Entity
@Table(name="comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public int id;
@ManyToOne
private Entry entry;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public Entry getEntry() {
return entry;
}
public void setEntry(Entry entry) {
this.entry = entry;
}
}
我编写了一个测试来测试关联映射:
@Test
@Transactional
public void testContainsComment() {
/* I inserted already an entry and a comment for the entry into the database */
Entry entry = entryDao.getById(1);
boolean containsComment = entry.containsComment(1); // -> Here I get the following exception: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [public int com.mypackage.Comment.id] by reflection for persistent property [com.mypackage.Comment#id] : 1
Assert.assertTrue(containsComment);
}
为什么会出现以下异常
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [public int com.mypackage.Comment.id] by reflection for persistent property [com.mypackage.Comment#id] : 1
我错过了什么
其他信息 我应该提到,我可以使用getComments()方法访问comments集合。comments集合上的size()也起作用。唯一的问题是contains()方法。注意,我将commentId作为参数传递给containsComment()-方法。我可以/应该传点别的吗
有趣的是,hibernate记录了contains方法的正确查询
Hibernate: select 1 from comments where entry_id =? and id =?
# 1 楼答案
您使用方法
comments.contains()
的方式不正确comments
是Comment
的List
,因此需要将Comment
传递给contains()
方法comments.contains(new Comment(1))
显然,这段代码找不到任何东西,因为,}以获得有效的行为
contains()
使用equals(在本例中,通过引用)来检查对象的相等性。您可以重写equals()
和hashCode()
{或者,如果需要检查大量注释,或者查询数据库以检查特定的
Comment
id,则可以使用循环并逐个元素检查id相等性,或者使用带有id的临时集合# 2 楼答案
添加setter您的
Entry.class
属性comments
未添加setter将此添加到
Entry.class
编辑 像这样重构
containsComment
方法# 3 楼答案
试试这个:
在Comment类中,在@ManyToOne之后,指定一个@JoinColumn类似:
也请检查此post