【问题标题】:How to fix LazyInitializationException - no Session in Spring application?如何修复 LazyInitializationException - Spring 应用程序中没有会话?
【发布时间】:2023-03-12 12:32:02
【问题描述】:

在 Spring 应用程序中,有时我会遇到异常:client.getCatIdSet 上的 org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role ... could not initialize proxy - no Session。我无法测试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;
    }

【问题讨论】:

    标签: java spring transactions spring-transactions


    【解决方案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> 
    

    【讨论】:

      猜你喜欢
      • 2014-05-22
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多