我有两个实体: 条目和评论。一篇文章有 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() 方法访问评论集合。评论集合上的 size() 也有效。唯一的问题是 contains() 方法。请注意,我将 commentId 作为参数传递给 containsComment() 方法。我可以/应该传递其他东西吗?
有趣的是,hibernate 记录了 contains 方法的正确查询。
Hibernate: select 1 from comments where entry_id =? and id =?
最佳答案
您以错误的方式使用了 comments.contains()
方法。
private List<Comment> comments = new ArrayList<>();
comments
是 Comment
的 List
,因此您需要将 Comment
传递给 contains()
方法
comments.contains(new Comment(1))
显然,这段代码什么也没找到,因为 contains()
使用 equals(在本例中是通过引用)来检查对象的相等性。您可以覆盖 Comment
的 equals()
和 hashCode()
以获得有效的行为。
或者,如果您需要检查大量评论,或者查询数据库以检查特定评论
,您可以使用循环并逐个元素检查 id 相等性,或者使用带有 id 的临时集ID。
关于java - Hibernate 额外懒惰不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534158/