[英]Hibernate Lazy Loading - getting Listitems in List
I am currently experimenting with hibernate 5 in my java application. 我目前正在我的Java应用程序中尝试使用休眠5。 I have the following problem:
我有以下问题:
I have two pojos/models: 我有两个pojos /模型:
@Entity(name="Categories")
public class Category {
@javax.persistence.Id
private int Id;
private String Name;
@OneToMany(mappedBy = "category",cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private List<Link> links = new ArrayList<>();
// ... getters and setters..
}
@Entity(name="Links")
public class Link {
@javax.persistence.Id
private int Id;
private String Name;
private String Url;
@ManyToOne
@JoinColumn(name="CategoryId")
private Category category;
// ... getters and setters..
}
Now i want to get all categories with links in it. 现在我想获得所有带有链接的类别。 My dao for that is the following:
我的建议如下:
public Iterable<Category> getCategories() {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.getCurrentSession();
session.getTransaction().begin();
String hsql = "from " + Category.class.getName() + " e";
Query<Category> query = session.createQuery(hsql);
List<Category> cats = query.getResultList();
cats.forEach(item -> Hibernate.initialize(item.getLinks()));
session.getTransaction().commit();
return cats;
}
This is working but i think this is a bad solution for getting all Links from all categories. 这是可行的,但我认为这对于从所有类别获取所有链接都是一个不好的解决方案。 I already experimented with "JOIN FETCH".
我已经尝试过“ JOIN FETCH”。
For example if i use: 例如,如果我使用:
String hsql = "from " + Category.class.getName() + " e JOIN FETCH e.links l
I will get all results twice... What is the best practise to get all Items from the list "links" from all Categories of my List? 我将两次获得所有结果...最佳实践是从列表的所有类别中的“链接”列表中获取所有项目吗?
I hope this question is not too easy but i cant find anything helpful regarding this. 我希望这个问题不太容易,但是我找不到关于此的任何帮助。
you could try using this make sure to use this inside the transcation boundary 您可以尝试使用此方法,并确保在交易边界内使用此方法
List<Link> totalLinks = cats.stream().map(cat -> cat.getLinks()).
flatMap(l -> l.stream()).collect(Collectors.toList());
Instead of fetch=FetchType.LAZY
you could use fetch=FetchType.EAGER
and hibernate will resolve all the links directly on load. 而不是
fetch=FetchType.LAZY
您可以使用fetch=FetchType.EAGER
和休眠状态将直接解决负载上的所有链接。
Depends on the use case if you want to use this. 如果要使用,取决于使用情况。 For small data sets that is absolutely ok.
对于小型数据集,绝对可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.