简体   繁体   English

在 Spring boot 和 JPA 中更新 n-to-m 关系的正确方法是什么?

[英]Whats the correct way to update a n-to-m relation in Spring boot and JPA?

I have 2 entities foo and bar in a n-to-m relation.我有 2 个实体foobar处于 n 对 m 关系中。 Here is Foo:这是福:

@Entity
@Table(name = "foo")
public class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "name")
    private String name;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.DETACH)
    @JoinTable(
            name = "foo_bars",
            joinColumns = {@JoinColumn(name = "foo_name", referencedColumnName = "name")},
            inverseJoinColumns = {@JoinColumn(name = "bar_name", referencedColumnName = "name")}
    private Set<Bar> bars;

    public Foo() {}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Bar> getBars() {
        return bars;
    }

    public void setBars(Set<Bar> bars) {
        this.bars = bars;
    }

}

and this is Bar:这是酒吧:

@Entity
@Table(name = "bar")
public class Bar implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "name")
    private String name;

@ManyToMany(mappedBy = "bar", fetch = FetchType.EAGER)
@JsonIgnore
private Set<Foo> foos;

    public Bar() {}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Foo> getFoos() {
        return foos;
    }

    public void setFoos(Set<Foo> foos) {
        this.foos = foos;
    }

}

So my relation is called foo_bars with columns foo_name,bar_name .所以我的关系被称为foo_barsfoo_name,bar_name How do I update rows in foo_bars?如何更新 foo_bars 中的行?

EDIT: eg How to add a specific Foo to an existing bar with name 'xyz'?编辑:例如,如何将特定的 Foo 添加到名为“xyz”的现有栏? My attempt does not persist a new entry of foo_bars:我的尝试不会保留 foo_bars 的新条目:

Foo newFoo = new Foo();
newFoo.setName("a new foo");
newFoo.setBars(new HashSet());

Optional<Bar> barOpt = this.barRepository.findByName("xyz");
if (barOpt.isPresent()) {
    Bar toUpdate = barOpt.get();
    Set<Foo> foos = toUpdate.getFoos();
    foos.add(newFoo);
    toUpdate.setFoos(foos);
    this.barRepository.save(toUpdate);
}

You don't have to update the table directly.您不必直接更新表。

Through your @ManyToMany mapping Hibernate will take care of the relationship table.通过您的@ManyToMany映射,Hibernate 将处理关系表。

So when you add or remove entities to or from the collection Hibernate will update the records.因此,当您在集合中添加或删除实体时,Hibernate 将更新记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM