【问题标题】:Hibernate Many to one updating foreign key to null休眠多对一更新外键为空
【发布时间】:2014-03-23 13:44:22
【问题描述】:

我正在尝试使我的 @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 对象上...

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

非常感谢。

【问题讨论】:

    标签: java hibernate one-to-many many-to-one


    【解决方案1】:

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

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

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

    ...

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

    【讨论】:

    • 这里的问题是性能,如果你使用 EAGER,如果有很多行,你应该研究 table Pitch,但如果只是一个值的字典,这不是一个坏做法。
    猜你喜欢
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多