Hibernate多对一更新外键为null

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate多对一更新外键为null相关的知识,希望对你有一定的参考价值。

我想让我的@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确实设置在Pitch Object上...

仅供参考,我不是直接更新从DB加载的原始对象。这些域被映射到一个Model类,这是UI更新的内容。因此,在保存/更新时,我将值映射回新的域对象,包括如下所示的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?

非常感激。

答案

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

在双向关联中,您必须始终拥有所有者方和反方。使用mappedBy属性标记反面。在OneToMany关联中,反面必须是单边:

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

...

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

以上是关于Hibernate多对一更新外键为null的主要内容,如果未能解决你的问题,请参考以下文章

Hibernate,关系映射的多对一单向关联多对一双向关联一对一主键关联一对一外键关联多对多关系关联

hibernate之一对多,多对一

Hibernate--一对多/多对一

Hibernate 一对一关联关系

Hibernate单向“多对一”关联

Hibernate—— 一对多 和 多对多关联关系映射(xml和注解)总结(转载)