Hibernate:保存子实体

时间:2016-08-26 14:09:36

标签: java hibernate jpa orm

我有两张桌子:

父表: phasesetups

| id  | created             | modified            | name                                            | model | model_id | uid  | description      | old_model_id |
+-----+---------------------+---------------------+-------------------------------------------------+-------+----------+------+------------------+--------------+
| 556 | 2016-08-26 14:08:07 | 2016-08-26 14:08:07 | EQ: 1  |  PREP: 2  |  ANALYSIS: 3  |  BIOINF: 4 | Order |        0 | uid  | first phasesetup | ng_2004741   |

子表:阶段

+------+---------------------+---------------------+------+-----------+---------------+--------------+
| id   | created             | modified            | name | duration  | phasesetup_id | phasetype_id |
+------+---------------------+---------------------+------+-----------+---------------+--------------+
| 2263 | 2016-08-26 14:08:07 | 2016-08-26 14:08:07 | NULL | 345600000 |          NULL |            4 |
| 2266 | 2016-08-26 14:08:07 | 2016-08-26 14:08:07 | NULL |  86400000 |          NULL |            1 |
| 2269 | 2016-08-26 14:08:07 | 2016-08-26 14:08:07 | NULL | 172800000 |          NULL |            2 |
| 2272 | 2016-08-26 14:08:07 | 2016-08-26 14:08:07 | NULL | 259200000 |          NULL |            3 |
+------+---------------------+---------------------+------+-----------+---------------+--------------+

我的意见: 1.PhaseSetup

@Entity
@Table(name = "phasesetups")
public class PhaseSetup extends AbstractEntity {

    @Column(name = "model_id")
    private Long modelId;

    @Column(nullable = false)
    private String model;

    @Column(name = "old_model_id")
    private String oldModelId;

    @Column(nullable = false)
    private String uid;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "phasesetup_id", cascade = CascadeType.PERSIST)
    private Set<Phase> phases;

第二阶段:

@Entity
@Table(name = "phases")
public class Phase extends AbstractEntity {

    @ManyToOne
    @JoinColumn(name = "phasetype_id")
    private Phasetype phasetype;

    private Long phasesetup_id;

    private Long duration;

问题:我想保存阶段和phasesetups,我可以保存它们但是phasesetup_id仍然是null。

是不是应该自动保存phasesetup_id?因为它是由phasesetup_id映射的?

请帮帮我,我在这里失踪了什么? 感谢。

2 个答案:

答案 0 :(得分:1)

您在private Long phasesetup_id;中不需要Phase。按如下所示更改PhaseSetup

   @OneToMany(fetch = FetchType.EAGER, mappedBy = "phasesetup_id", cascade = CascadeType.PERSIST)
    private Set<Phase> phases;

   @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
   @JoinColumn(name = "phasesetup_id")
private Set<Phase> phases;

在单向JPA关系中不需要mappedBy。阅读here

答案 1 :(得分:0)

需要定义PhaseSetups和Phase Entity中的Phase之间的关系。因此,将Phase中的phasesetup_id定义为像

这样的对象

@ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name =&#34; phasesetup_id&#34;,referencedColumnName =&#34; uid&#34;,insertable = true,updatable = true) private PhaseSetup phasesetup;

我想,它会解决你的问题。