gpt4 book ai didi

java - 如何修复 LazyInitializationException - Spring 应用程序中没有 session ?

转载 作者:行者123 更新时间:2023-12-02 09:57:36 27 4
gpt4 key购买 nike

在Spring应用程序中,有时我会遇到异常:org.hibernate.LazyInitializationException:未能延迟初始化角色集合...无法初始化代理-在client.getCatIdSet<上没有 session /。我无法测试 fetch = FetchType.EAGER 是否修复问题,因为此错误并不经常发生。类有 Transactional 注解,方法是公共(public)的。我该如何解决这个异常?

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

最佳答案

在您的 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>

关于java - 如何修复 LazyInitializationException - Spring 应用程序中没有 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55882857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com