我正在尝试使我的@OneToMany和@ManyToOne关系正确。
第1类:
@Entity public class IdeaProfile { @Id @GeneratedValue private int ideaProfileId; private String name; Date dateConcieved; @OneToOne @JoinColumn(name="statusCode") private Status status; @OneToMany(fetch=FetchType.EAGER, targetEntity=Pitch.class, cascade=CascadeType.ALL) @JoinColumn(name = "ideaProfileId") private List<Pitch> pitchs; ....getters and setters....
第2类:
@Entity public class Pitch { @Id @GeneratedValue private int id; @ManyToOne @JoinColumn(name = "ideaProfileId") private IdeaProfile ideaProfile; private Date date; private String notes; ....getters and setters....
当我加载或保存新记录时,这种关系似乎运行良好:
Hibernate: insert into IdeaProfile (dateConcieved, genreCode, name, statusCode) values (?, ?, ?, ?) Hibernate: insert into Pitch (date, ideaProfileId, notes) values (?, ?, ?) Hibernate: update Pitch set ideaProfileId=? where id=?
但是,当我尝试更新该记录时,它将尝试将IdeaProfileId设置为null:
Hibernate: update IdeaProfile set dateConcieved=?, genreCode=?, name=?, statusCode=?, where ideaProfileId=? Hibernate: update Pitch set date=?, ideaProfileId=?, notes=? where id=? Hibernate: update Pitch set ideaProfileId=null where ideaProfileId=?
当我调试时,我可以看到IdeaProfileId确实在音高对象上设置了…
仅供参考,我不是直接更新从数据库加载的原始对象。这些域映射到UI更新的Model类。因此,在保存/更新时,我将值映射回新的域对象,包括如下所示的ID:
IdeaProfile domain = new IdeaProfile(); domain.setId(model.getIdeaProfileId()); domain.setName(model.getName()); domain.setStatus(model.getStatus()); domain.setDateConcieved(Date.valueOf(model.getDateConvieved())); for (PitchModel pitch : model.getPitches()) { Pitch pitchDomain = new Pitch(); pitchDomain.setId(pitch.getId()); pitchDomain.setDate(Date.valueOf(pitch.getDate())); pitchDomain.setNotes(pitch.getNotes()); pitchDomain.setIdeaProfile(domain); if(domain.getPitchs() == null ) { domain.setPitchs(new ArrayList<Pitch>()); } domain.getPitchs().add(pitchDomain); } openSession(); session.beginTransaction(); session.saveOrUpdate(domain); session.getTransaction().commit(); closeSession();
有谁知道我做错了什么,所以Hibernate导致更新尝试将IdeaProfileId设置为null?
非常感激。
您在这里没有双向关联。您有两个独立的关联,每个关联都错误地映射到同一列。
在双向关联中,必须始终具有所有者侧和反向侧。反面使用mappingBy属性标记。在OneToMany关联中,反面必须是一侧:
@OneToMany(mappedBy="ideaProfile", fetch=FetchType.EAGER, cascade=CascadeType.ALL) private List<Pitch> pitchs;
…
@ManyToOne @JoinColumn(name = "ideaProfileId") private IdeaProfile ideaProfile;