我有一個類Patient擁有一個Id集合和一個文件夾集合。當我嘗試自己保存一個文件夾時,由於Patient的id集合,它會拋出LazyInitializationException。LazyInitializationException當保存一個關係的一方
Patient類看起來是這樣的:
@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)
更改爲'FetchType.EAGER'。 –
這不是一個有效的解決方案,因爲我不想過載內存,每次加載病人時,我都不想加載它的所有ID,因爲它們包含大量數據。 – diminuta
'Hibernate.initialize(folder.getPatient()。getIds());'? –