Search code examples
javahibernatejpalazy-initialization

Hibernate circled entities


straight to the point: I have a group that contains projects. I want that association to be handle with a foreign key, which is why it has a mappedby tag. My issue is that if I query for groups I get into an inifinite loop where the group lists the projects which contain the group which list the project which again contains the group.....and so on. My entities (minimal version):

@Entity
public class DBGroup {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;

   @OneToMany(mappedBy = "group",cascade=CascadeType.ALL,fetch = FetchType.EAGER)
   private List<Project> projects = new ArrayList<>();
}


@Entity
public class Project {
  @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

@ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn//added this because i read somewhere this would help somehow but it didnt
    private DBGroup group;
}

Can anyone help on how to avoid that loop? If I change the fetchtype to lazy in DBGroup I get a LazyInitializationEXception.

Any help is appreciated.


Solution

  • When the transaction ends you obtain an LazyInitializationEXception for all objects you didn't fetch.

    If you get the object with a query add join fetch like:

    select p from Project p join fetch p.group g

    You can fetch a list via code calling the size method before exit the ejb.

    Use FetchType.LAZY all time you can for prevent this especially if is a list.