网上乱七八糟的太乱!各种不能用,各种错!
本博文实现:双向多对一注解配置,在多端维护关系(在多端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<>();