我用hbiernate annation写的代码,维护多对多关系时,出了个奇怪的问题:
1:Operator.java
@Entity
//@Table(name="operator")
public class Operator implements java.io.Serializable,IfTableModel {
private static final long serialVersionUID = 1L;
public static final String [] column={"编号","姓名","其他信息"};
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "name",unique=true)
private String name;
@Column(name = "msg")
private String msg;
@ManyToOne(targetEntity=base.Role.class)//,cascade={CascadeType.PERSIST,CascadeType.MERGE} )
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinColumn(name="RoleId")
private Role role;
@ManyToMany(targetEntity=base.Department.class)
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinTable(
name="operator_department ",
joinColumns={@JoinColumn(name="OperatorId")},
inverseJoinColumns={@JoinColumn(name="DepartId")}
)
private List<Department> departs=new ArrayList();
}
2epartment.java
@Entity
@Table(name = "department")
public class Department implements java.io.Serializable,IfTableModel {
private static final long serialVersionUID = 1L;
public static final String Id = "id";
public static final String Name = "name";
public static final String [] column={"编号","部门名称"};
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@ManyToMany(targetEntity=base.Operator.class,mappedBy="departs")
private List<Operator> operators=new ArrayList();
}
关系说明:operator和department是多对多的关系,其中,operator端负责关系的维护
3:对operator和department操作的代码
Transaction tx2= se.beginTransaction();
BaseUtil u=new BaseUtil();
List<Department> departs=u.getDepartments();
List<Operator> opers=u.getOperators();
opers.get(0).getDeparts().add(departs.get(0));
opers.get(0).getDeparts().add(departs.get(1));
tx2.commit();
现在期望的sql代码是:insert into operator_department (OperatorId, DepartId) values (?, ?)
这里出现一个奇怪的问题是,现在总是先
delete from operator_department where OperatorId=?
然后才把所有原来的关系重新插入一遍
insert into operator_department (OperatorId, DepartId) values (?, ?)
insert into operator_department (OperatorId, DepartId) values (?, ?)
insert into operator_department (OperatorId, DepartId) values (?, ?)
这样严重影响性能,各位高人帮忙看看什么原因啊?