LazyInitializationException in selectManyCheckbox on @ManyToMany(fetch=LAZY)

ⅰ亾dé卋堺 提交于 2019-11-27 15:09:01
BalusC

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.

I fix it only by specifie

<f:attribute name="collectionType" value="java.util.LinkedHashSet" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!