1

I'm developing a Struts2 + Hibernate + Spring application. I'm trying to load the user permissions into my session in order to recover them into the specific jsp.

The workflow is this one:

  1. The user logs in
  2. The user group is loaded Eagerly by hibernate

Here is the code from User class.

@JoinColumn(name = "id_user_group", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY, targetEntity = UserGroup.class)
public UserGroup getUserGroup() {
    return userGroup;
}
  1. From the User group i recover another EAGER relation

Here is the code from UserGroup class

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "user_section_permission", joinColumns = {
    @JoinColumn(name = "id_user_group", nullable = false, updatable = false)},
        inverseJoinColumns = {
            @JoinColumn(name = "id_section_permission",
                    nullable = false, updatable = false)})
public List<SectionPermission> getSectionPermissions() {
    return sectionPermissions;
}
  1. The user is saved into the session. When the login action redirects the user to his dashboard then a refreshPermissions method is called

Here is the code:

UserGroup userGroup = ((User) session.get("user")).getUserGroup();

    Map<String, Section> permissions = new HashMap<>();
    List<SectionPermission> sectionPermissions = userGroup.getSectionPermissions();
    for (SectionPermission sectionPermission : sectionPermissions) {
        permissions.put(sectionPermission.getCode(), sectionPermission.getSection());
    }
    session.put("permissions", permissions);

I think it's easy to understand that I simply create a map with the permission code and his relative section (in order to populate the menu and so on.

And now the problem... My tomcat shows the permission attribute as empty

Tomcat manager image

But magically if I add a LOG.debug("Perm: {}", new Object[]{sectionPermission.getCode(), sectionPermission.getSection()}); inside the for loop then the permissions appear...

Tomcat manager image

What's happening? Am I doing something wrong with Hibernate or Spring?

IlGala
  • 3,331
  • 4
  • 35
  • 49

1 Answers1

2

You're using Lazy loading, so the permissions don't get loaded until you reference them. That is happening in the logging line.

Andres
  • 10,561
  • 4
  • 45
  • 63
  • 1
    I was editing my question writing that `getSection` has a LAZY fetch type... But I want to keep it lazy if possible... Do you know how can I initilize them when needed like in this example? – IlGala Oct 27 '15 at 17:40
  • @IlGala http://stackoverflow.com/questions/15359306/how-to-load-lazy-fetched-items-from-hibernate-jpa-in-my-controller – Andres Oct 27 '15 at 17:42