The problem
Recently I ran into a problem using PrimeFaces SelectManyButton component. I have a User entity which has a collection of Groups.
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "user_group")
private @Enumerated(STRING) Set<UserGroup> userGroups = new HashSet<>();
I have a JSF page where user can be edited and the groups can be assigned to the user. When I pressed the save button I got the error message:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection, could not initialize proxy – no Session
If you use JPA sooner or later you will meet this error message, it was not unfamiliar for me. In this case Hibernate Session has nothing to do with this error.
In the JakartaEE specification you can find there is a collectionType attribute.
“Optional attribute that is a literal string that is the fully qualified class name of a concrete class that implements java.util.Collection, or an EL expression that evaluates to either 1. such a String, or 2. the Class object itself.”
Solution
Add collectionType attribute solved the problem. In my case Group is stored in a Set so HashSet is working fine.
<p:selectManyButton value="#{users.selection.userGroups}">
<f:attribute name="collectionType" value="java.util.HashSet" />
...
</p:selectManyButton>