1

I have 2 entities related to each other like this:

EntityA {
    (...)
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "entityA")
    private List<EntityB> listOfBs; 
    (...)
    // getters and setters
}

EntityB {
    (...)
    @ManyToOne
    @JoinColumn(name = "idEntityA)
    private EntityA entityA; 
    (...)
    // getters and setters
}

The related business rule is: EntityA can have one or more EntityB, hence the @OneToMany. Each EntityB can only be assigned to one EntityA. Initially.

The application's information flow is this - first you get a list of EntityA, then you select one EntityA so you can get a list of all EntityBs associated to the selected EntityA.

The problem is: If I have only one EntityB per EntityA, I get the correct behavior on the first screen. If I have more than one EntityB associated to an EntityA, the first screen shows a number of EntityA equals to the number of EntityB associated with it.

But if I change the annotation of EntityA from @OneToMany(fetch = FetchType.EAGER, mappedBy = "entityA") to @OneToMany(fetch = mappedBy = "entityA"), the correct behavior is shown in the first screen (one entityA regardless how many entityBs are associated with it), but when I try to access it I get the following error:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: b.c.m.h.m.EntityA.listOfBs, could not initialize proxy - no Session

What's going on here?

EDIT - The solution offered on the other question does not solves my issue.

gtludwig
  • 5,411
  • 10
  • 64
  • 90
  • I would guess the problem lies within your display code and you iterate over first each `EntityA` and then each `EntityB` of the current `EntityA`. Please check this first! Edit: The case with the `LazyInitializationException` has nothing to do with your "business" rules, it is just standard Hibernate behavior that when the database session is finished you can't post-load entities. – Smutje Oct 13 '16 at 14:05
  • @Smutje, thank you your input. Debugging the application, I got an `com.sun.jdi.InvocationException occurred invoking method` on the `List that my controller uses to populate the table on the listOfEntityB's screen. – gtludwig Oct 13 '16 at 14:15
  • Possible duplicate of [Solve "failed to lazily initialize a collection of role" exception](http://stackoverflow.com/questions/11746499/solve-failed-to-lazily-initialize-a-collection-of-role-exception) – iamorozov Oct 13 '16 at 14:17
  • Removing the `FetchType.EAGER`, it is clear why you get a `LazyInitializationException`, but what about the display of `EntityA` traversing each entities `EntityB`? – Smutje Oct 13 '16 at 14:18
  • I did that. The shown amount of `EntityA` is correct, but I get the exception `org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: b.c.m.h.m.EntityA.listOfBs, could not initialize proxy - no Session` when accessing an `EntityA`. – gtludwig Oct 13 '16 at 14:22

0 Answers0