保存关系的一侧时{LazyInitializationException

时间:2017-08-22 08:59:20

标签: java spring hibernate lazy-initialization

我有一个具有Id集合和一组文件夹的患者。当我尝试自己保存文件夹时,由于Patient的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);
    ...
}

当它尝试用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)

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

问题在于您尝试在会话之外保存OrUpdate。 Hibernate.initialize会初始化您的患者集合,以便在saveOrUpdate之前使用,或者您可以手动打开休眠会话,事务,提交并关闭资源。

尝试这样:https://www.mkyong.com/hibernate/hibernate-transaction-handle-example/