使用@MapsId持久化@OneToOne子实体会在休眠中引发“错误:分离的实体传递以持久化”
2022-09-04 04:39:26
我读了 https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/。我尝试了建议配置,如(使用弹簧数据JPA,休眠5.0作为供应商):
public class PaperSubjectType{
@Id
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private PaperSetting paperSetting;
..
}
class PaperSetting{
@Id
@GeneratedValue
private Long id;
..
}
首先,我尝试了这个例子:
PaperSetting paperSettingInDb = paperSettingRepository.findOne(1);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setSubjectCode("91");
paperSubjectType.setPaperSetting(paperSettingInDb);
paperSubjectTypeRepository.save(paperSubjectType);
错误:分离的实体传递给持久化:纸张设置。它似乎休眠采取 PaperSetting 作为分离时级联
2 如果我想同时创建PaperSubjectType和PaperSetting,我需要这样做吗:
PaperSetting paperSetting = new PaperSetting();
paperSetting.setxx;
PaperSetting paperSettingInDbNew = paperSettingRepository.save(paperSetting);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setPaperSetting(paperSettingInDbNew);
paperSubjectTypeRepository.save(paperSubjectType);
或者我应该在这种情况下使用双向?谢谢!