简体   繁体   中英

Hibernate Lazy Loading - getting Listitems in List

I am currently experimenting with hibernate 5 in my java application. I have the following problem:

I have two pojos/models:

@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".

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.

Depends on the use case if you want to use this. For small data sets that is absolutely ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM