LazyInitializationException in selectManyCheckbox on @ManyToMany(fetch=LAZY)

后端 未结 2 1652
梦毁少年i
梦毁少年i 2020-12-03 18:34

What is the best way to handle multiple chackboxes when you nead to fill a JPA M:N relation ... for example I have an JPA entity Hardware and the entity Connectivity.

相关标签:
2条回答
  • 2020-12-03 18:46

    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">
    

    See also org.hibernate.LazyInitializationException at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValuesForModel.

    0 讨论(0)
  • 2020-12-03 18:54

    I fix it only by specifie

    <f:attribute name="collectionType" value="java.util.LinkedHashSet" />
    
    0 讨论(0)
提交回复
热议问题