【问题标题】:How to cascade insert child entities when child has composite key子实体具有复合键时如何级联插入子实体
【发布时间】:2019-10-30 17:19:49
【问题描述】:

我从来自 EF 的 JPA 开始,并尝试在子级具有复合键的情况下进行简单的主从插入。

foo 插入正常(没有错误,Hibernate 只是将 insert 打印到 Foo 语句中),但是 bar 被忽略了。 我找到了this question,其中在键中定义了关系,但我也无法让它工作(与我原来的解决方案相同的问题,没有例外,也没有子插入)。

我的代码目前如下所示:

@Entity
public class Foo {
    @Id
    private String fooID;

    @OneToMany(mappedBy = "foo")
    private List<Bar> bars = new ArrayList<>();

    // getter, setter,...
}

@Entity
public class Bar {

    @EmbeddedId
    private BarId id;

    public Bar(){
        this.id = new BarId();
    }

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @MapsId("fooID")
    @JoinColumn(name = "fooID", referencedColumnName = "fooID")
    private Foo foo;

    public void setFooId(String fooId){
        this.id.setFooId(fooId);
    }

    public void setBarNo(int barNo){
        this.id.setBarNo(barNo);
    }

    // other getter, setter,...
}

@Embeddable
public class BarId implements Serializable {
    private String fooID;
    private int barNo;

    // getter, setter, hashCode, equals,...
}

// ...
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();

Foo newFoo = new Foo();
newFoo.setFooID("baz");

Bar newBar = new Bar();
newBar.setFooId(newFoo.getFooId()); // even necessary?
newBar.setBarNo(1);
newBar.setFoo(newFoo);

newFoo.getBars().add(newBar);

em.persist(newFoo);
em.getTransaction().commit();

如果这有什么不同的话,我正在使用 JPA 2.2 和 Hibernate 5.4。

为了更好地阐明我所追求的(对于所有了解一点 EF 的人):

foo.HasKey(f => f.FooID);
foo.HasMany(f => f.Bars).WithOne(b => b.Foo).HasForeignKey(b => b.FooID);

bar.HasKey(b => new {b.FooID, b.BarNo});

我必须进行哪些更改才能使其正常工作? 还是我一开始就完全错误地使用 JPA?

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    想通了:cascade = CascadeType.PERSIST 必须放在主端,而不是像这样放在关系的细节端:

    @OneToMany(mappedBy = "foo", cascade = CascadeType.PERSIST)
    private List<Bar> bars = new ArrayList<>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 2012-06-17
      • 1970-01-01
      • 2020-11-28
      • 2019-11-24
      相关资源
      最近更新 更多