使用id仅写入多对多联接表

时间:2018-06-14 11:09:03

标签: java jpa

@ManyToOne关系中,可以通过设置相关表的id来处理关系的写入:

@Entity
public class Foo{
    @GeneratedValue
    @Id
    private Long id;
    @Column(name = "bar_id")
    private Long barId;
    @ManyToOne
    @JoinColumn(insertable = false, updatable = false)
    private Bar bar;
    // ...
}

@Entity
public class Bar{
    @GeneratedValue
    @Id
    private Long id;
    @OneToMany(mappedBy = "bar")
    private List<Foo> foos;
    // ...
}

在许多情况下(例如:构建Bar的实例很困难时)这是保持与Foo相关的Bar而非设置foo.bar的更好方法到一个空实例并设置该实例的id。如何在@ManyToMany关系中实现类似的东西?

1 个答案:

答案 0 :(得分:0)

@ManyToOne示例类似,您只能通过设置barIds字段来保持关系,而bars字段只读:

@Entity
public class Foo {
    @GeneratedValue
    @Id
    private Long id;
    @ElementCollection
    @CollectionTable(name = "foo_bars", joinColumns = @JoinColumn(name = "foos_id", referencedColumnName = "id"))
    @Column(name = "bars_id")
    private Set<Long> barIds;
    @ManyToMany
    @JoinColumn(insertable = false, updatable = false)
    private Set<Bar> bars;
    // ...
}