1

I have hibernate entity GeUser this entity have ManyToMany relation to Pick entity, this entity has OneToOne relations to ALgo entity and this entity has ManyToMany relation with DbMatch entity. My goal is get GeUser entity but without picks.algo.matches . I want use GeUser object on my web app, but for me data about algo matches is not required, so I want to skip it before is loaded from database.

GeUser entity:

...
@Entity
public class GeUser {
   ....
   @ManyToMany
   private List<Pick> picks = new ArrayList<Pick>(0);
   ...

Pick entity:

@Entity
public class Pick {
   ...
   @OneToOne
   private Algo algo;
   ...

Algo entity:

...
@Entity
public class Algo{
    ...
    // I want to skip this when GeUser entity is loading from db. Should be e.g. matches == null
    @ManyToMany
    protected List<DbMatch> matches = new ArrayList<DbMatch>(); 
    ...

GeUser dao method:

public GeUser getUser(int user_id) {

    Criteria criteria = session.createCriteria(GeUser.class);
    criteria.add(Restrictions.eq("user_id",user_id));

    List<GeUser> users = criteria.list();

    if (users.size() > 0) {
        return users.get(0);
    } else {
        return null;
    }

}
Edgaras Karka
  • 5,020
  • 10
  • 38
  • 84

1 Answers1

4

This is a simple situation which can be solved with the help of Lazy loading. You can specify FetchType.LAZY matches inside Algo. matches will be loaded only when you access it within an active session.

...
@Entity
public class Algo{
    ...
    // I want to skip this when GeUser entity is loading from db. Should be e.g. matches == null
    @ManyToMany(fetch = FetchType.LAZY )
    protected List<DbMatch> matches = new ArrayList<DbMatch>(); 
    ...

For more in details about Lazy loading, please follow these tutorials:

Hope it helps, feel free to comment if you need further help!

Community
  • 1
  • 1
SyntaX
  • 1,942
  • 13
  • 27
  • Thanks you have shown right direction for me, after read about hibernate lazy loading I understand how it work, but now I have new issue about how to not pass matches to web app using spring controller and jackson and answer is here http://stackoverflow.com/questions/28746584/how-to-avoid-lazy-fetch-in-json-serialization-using-spring-data-jpa-spring-web – Edgaras Karka Nov 19 '15 at 11:07