Hibernate OneToMany不会获取所有子实体。有时它会从注释列表中检索所有值,有时则不会。 如果我遗漏了一些东西,请帮助我理解。
@Entity
@Data
@Table(name = "Post")
public class Post implements Serializable {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", nullable = false, unique = true)
private String id;
@Column(name = "name")
private String postname;
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy="post",orphanRemoval = true)
private List<Comment> comments = new ArrayList<>();
//getters and setters
}
@Entity
@Data
@Table(name = "comments")
public class Comment implements Serializable{
private static final long serialVersionUID = -4522532272183748926L;
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", nullable = false, unique = true)
private String id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "comment_id", nullable = false)
private Post post;
@Column(name = "sequence", nullable = false)
private Long sequence;
//getters and setters
}
When I fetch , comments list from a post.It is retrieving only one comments entity.Even there are more than one.
有时它会给所有子实体,有时只给一个。
List<Comment> list = getPost().getComments();
System.out.println("Size of list : "+getPost().getComments().size()); //giving only 1 comment entity , even there are two entities
for(int i = 0;i< list.size();i++) {
Comment rc = getPost().getComments().get(i);
}
这是从DB获取帖子列表的方法。在数据库中有大约5000个帖子,当一个特定的帖子(一个给一个实体一次,不同运行中的所有实体)的第一个元素这个List,然后检索所有子实体,但是当它位于列表中间的某个位置时,只检索一个子实体。
@Transactional(propagation=Propagation.REQUIRES_NEW)
public List<Post> getPostList(int firstResult, int maxResult){
List<Post> list = null;
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(Post.class);
try {
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResult);
criteria.addOrder(Order.asc("dateCreated"));
list=Collections.checkedList(criteria.list(), Post.class);
}catch(Exception e) {
e.printStackTrace();
}finally {
if(session!=null) {
session.close();
}
}
return list;
}