代码之家  ›  专栏  ›  技术社区  ›  rioubenson

Hibernate多对一将外键更新为null

  •  4
  • rioubenson  · 技术社区  · 10 年前

    我正在努力纠正我的@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设置为空:

    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确实设置在Pitch对象上。。。

    仅供参考,我没有直接更新从DB加载的原始对象。这些域被映射到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?

    非常感谢。

    1 回复  |  直到 10 年前
        1
  •  18
  •   Martin Konecny    7 年前

    这里没有双向关联。您有两个独立的关联,每个关联都错误地映射到同一列。

    在双向关联中,必须始终具有所有者侧和反向侧。反向侧使用mappedBy属性进行标记。在OneToMany关联中,反边必须是一个边:

    @OneToMany(mappedBy="ideaProfile", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    private List<Pitch> pitchs;
    

    ...

    @ManyToOne
    @JoinColumn(name = "ideaProfileId")
    private IdeaProfile ideaProfile;