在@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
关系中实现类似的东西?
答案 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;
// ...
}