Reputation: 375
In Spring application sometimes I have exception: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role ... could not initialize proxy - no Session
on client.getCatIdSet
. I can't test fetch = FetchType.EAGER
fix problem or not, because this error occurs not constantly. Class have Transactional
annotation, method is public. How I can fix this exception?
@Service
@Transactional
public class ChatService {
@PersistenceContext
EntityManager entityManager;
public BotRequest getBotRequest(MessageData messageData) {
Client client = messageData.getMessage().getClient();
Optional<CatId> mbCatId = Optional.ofNullable(client.getCatIdSet())
.orElse(Collections.emptySet())
.filter
...
This method invoke from:
@Service
public class SendMsgToCatBotService extends SendMsgToBotService {
@Override
protected BotRequest createBotRequest(MessageData messageData) {
return chatService.getBotRequest(messageData);
}
Client entity:
@Entity
@Table(name = "clients")
public class Client implements Serializable {
private int id;
private Set<CatId> catIdSet;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "clients_generation")
@SequenceGenerator(name = "clients_generation", sequenceName = "clients_id_seq", allocationSize = 1)
@Column(name = "id")
public int getId() {
return id;
}
@OneToMany(mappedBy = "client")
public Set<CatId> getCatIdSet() {
return catIdSet;
}
Upvotes: 0
Views: 108
Reputation: 11
In your web.xml, add below filter.
<filter>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Upvotes: 1