@manytomany
关系维护端
@Entity
public class Test1 {
public String id;
public String name;
public Set<Test2> test2;
@Id
@GenericGenerator(name = "idGenerator", strategy = "org.hibernate.id.UUIDGenerator")
@GeneratedValue(generator = "idGenerator")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(targetEntity=com.peyey.coo.model.Test2.class,
cascade = {javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.MERGE}
)
@JoinTable(name="test1test2",joinColumns=@JoinColumn(name="test1_id",referencedColumnName="id"),
inverseJoinColumns={@JoinColumn(name="test2_id",referencedColumnName="id")})
public Set<Test2> getTest2() {
return test2;
}
public void setTest2(Set<Test2> test2) {
this.test2 = test2;
}
}
关系被维护端:
@Entity
public class Test2 {
public String id;
public String name;
public Set<Test1> test1;
@Id
@GenericGenerator(name = "idGenerator", strategy = "org.hibernate.id.UUIDGenerator")
@GeneratedValue(generator = "idGenerator")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(
cascade = {javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.MERGE},
targetEntity=com.peyey.coo.model.Test1.class,
mappedBy="test2"
)
public Set<Test1> getTest1() {
return test1;
}
public void setTest1(Set<Test1> test1) {
this.test1 = test1;
}
}
增删改操作:
public void create(){
/*
* Test1维护关系
* 通过Test1级联增加Test2
*
*
*/
Test1 test1a=new Test1();
Test2 test2a=new Test2();
test2a.setName("test2a");
Test2 test2b=new Test2();
test2b.setName("test2b");
/**
* Test2的记录需要各自添加
* 所谓的级联增加,只是Test1对中间表而言
*/
test2Dao.save(test2a);
test2Dao.save(test2b);
Set<Test2> test2=new HashSet<Test2>();
test2.add(test2a);
test2.add(test2b);
test1a.setName("aaaa");
test1a.setTest2(test2);
test1Dao.save(test1a);
}
@Override
public void update() {
/**
* 删除中间表的记录
* 需要从Test1表出发,remove掉关联记录,然后更新
*/
Test1 test1=test1Dao.get("253ca3bc-6dc9-48a5-9948-067a40394497");
test1.getTest2().remove(test2Dao.get("c99c5a0d-6574-499a-ba59-e677afc1b8bf"));
test1Dao.update(test1);
}
@Override
public void delete() {
/**
* 删除维护关系的Test1,如果在关联表中有相关的记录,也会删除
*/
test1Dao.delete(test1Dao.get("253ca3bc-6dc9-48a5-9948-067a40394497"));
/**
* 如果需要删除Test2中的a记录,需要先找出Test2中a记录关联的Test1的记录列表,
* 然后通过Test1的那些记录逐个remove掉关联表中关于a的记录,然后更新Test1
* 最后再在Test2中删除a记录
*/
//test2Dao.delete(test2Dao.get("c99c5a0d-6574-499a-ba59-e677afc1b8bf"));
}
对于被维护端删除操作烦琐的问题需要解决。两端均维护关系?
比较习惯将manytomany拆分成两个manytoone。