【发布时间】: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