網上亂七八糟的太亂!各種不能用,各種錯!
本博文實現:雙向多對一註解配置,在多端維護關係(在多端set一端),刪除多端不影響一端,刪除一端級聯刪除多端
// 一的一端
@Entity
@Table(name = "one")
public class OneModel {
@Id
@GeneratedValue(generator = "generator")
@GenericGenerator(name = "generator", strategy = "uuid")
@Column(name = "id", length = 36)
private String id;
@OneToMany(mappedBy = "one", orphanRemoval = true)
Set<ManyModel> manySet = new TreeSet<>();
}
// 多的一端
@Entity
@Table(name = "many")
public class ManyModel {
@Id
@GeneratedValue(generator = "generator")
@GenericGenerator(name = "generator", strategy = "uuid")
@Column(name = "id", length = 36)
private String id;
@ManyToOne
@JoinColumn(name = "one_id")
private OneModel one;
}
// 如何關聯
// 首先創建一端的對象
OneModel one = new OneModel();
svc.addOne(one);
// 創建一個多端對象,並set進一端對象
ManyModel many1 = new ManyModel();
many1.setOne(one);
svc.addMany(many1);
// 再創建一個多端對象,並set進一端對象
ManyModel many2 = new ManyModel();
many2.setOne(one);
svc.addMany(many2);
通過上述操作之後,就實現了雙向多對一關聯,通過互相get即可取出對應關聯對象或對象集合。
若要刪除一端,還保留多端數據,則需要如下配置:
@OneToMany(mappedBy = "one", orphanRemoval = false)
Set<ManyModel> manySet = new TreeSet<>();
OneModel one = svc.getOneById("abc");
one.getManySet().forEach(m -> m.setOne(null));
svc.deleteOne(one);
補充一個問題:如果用的SpringMVC , 可能在返回頁面一端數據時會報錯,需要在一端添加JsonIgnore註釋 ,也就是不將多端集合json序列化
@OneToMany(mappedBy = "one")
@JsonIgnore // 加上該註釋即可
private Set<ManyModel> manySet = new TreeSet<>();