gpt4 book ai didi

java - 保存关系的一侧时出现 LazyInitializationException

转载 作者:行者123 更新时间:2023-12-02 12:20:29 24 4
gpt4 key购买 nike

我有一个 Patient 类,其中包含 Id 集合和文件夹集合。当我尝试单独保存文件夹时,由于患者的 id 集合,它会抛出 LazyInitializationException。

患者类别如下所示:

@Entity
@Table(name = "patient")
public class Patient implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@OneToMany(mappedBy = "patient", fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
private Set<Id> ids = new HashSet<Id>();

@OneToMany(mappedBy = "patient", fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
private List<Folder> folders = new ArrayList<Folder>();

...
}

文件夹类如下所示:

@Entity
@Table(name = "folder")
public class Folder implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@ManyToOne
@JoinColumn(name = "patient_id", referencedColumnName = "id")
private Patient patient;

}

然后我有一个服务类,它可以执行一些操作,然后保存一个像这样的文件夹:

@Override
@Transactional
public void importData(Data data) {

// do other things
Folder folder = new Folder();
// initialize folder values
...
folder.setPatient(patient);
folderDAO.save(folder);
...
}

当它尝试将文件夹保存在FolderDAO中时:

getHibernateTemplate().saveOrUpdate(folder);

它抛出:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: es.mycompany.myapp.Patient.ids, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:587)

最佳答案

使用cascade = ALL配置,您正在配置hibernate以在保存文件夹实体时更新患者列表/组,患者列表必须加载到内存中才能更新。您也许可以尝试删除 CASCADE = ALL 并手动管理任何列表和一组患者类别更新。

关于java - 保存关系的一侧时出现 LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45813202/

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