You need to fetch it while inside a transaction (thus, inside the service method), and not while outside a transaction (thus, inside e.g. JSF managed bean init/action method), that would thus throw a LazyInitializationException
.
So, your attempt
hardware.getConnectivities().size();
has to take place inside a transaction. Create if necessary a new service method for the purpose whereby you pass the entity which was obtained before in another transaction.
hardwareService.fetchConnectivities(hardware);
public void fetchConnectivities(Hardware hardware) {
hardware.setConnectivities(em.merge(hardware).getConnectivities()); // Becomes managed.
hardware.getConnectivities().size(); // Triggers lazy initialization.
}
An alternative would be to create a DTO for the purpose which has it eagerly fetched.
And then to save the selected items, make sure that you explicitly specify the selection component’s collectionType
attribute to a standard Java type rather than letting it autodiscover a JPA impl specific lazy loaded type such as org.hibernate.collection.internal.PersistentSet
in your specific case. JSF needs it in order to instantiate the collection before filling it with the selected items.
<p:selectManyCheckbox ... collectionType="java.util.LinkedHashSet">