如何修复LazyInitializationException-Spring应用程序中没有会话?

时间:2019-04-27 16:58:34

标签: java spring transactions spring-transactions

在Spring应用程序中,有时会有例外:org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role ... could not initialize proxy - no Session上的client.getCatIdSet。我无法测试fetch = FetchType.EAGER的修复问题,因为此错误不会经常发生。类具有Transactional批注,方法是公共的。我该如何解决此异常?

@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
                ...

此方法从以下位置调用:

@Service
public class SendMsgToCatBotService extends SendMsgToBotService {
    @Override
    protected BotRequest createBotRequest(MessageData messageData) {
        return chatService.getBotRequest(messageData);
    }

客户实体:

@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;
    }

1 个答案:

答案 0 :(得分:1)

在您的web.xml中,添加以下过滤器。

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