在hibernate里面调用session的delete方法以后无论这个被删除的对象有没有被人外键引用到都可以被删除并且此时的外键设为null也就是说他会自动帮我们去查看他被谁引用到了然后把引用全部去掉后再把自己删掉而在JPA里面如果调用EntityManagerremove方法时传进去的对象有被外键引用到则会失败因为JPA里面的实现就是直接执行delete语句也不管他有没有被外键引用此时当然会出错了
测试时候使用的两个类分别如下
举的例子是部门和员工的关系一个部门可以有多个员工然后把部门删掉的时候员工的部门属性就为null了不过按照严谨来说还是JPA的严谨一些这样可以防止误操作呵呵
部门的实体对象
/*
* To change this template choose Tools | Templates
* and open the template in the editor
*/
package comhadesleejpaentity;
import javaioSerializable;
import javautilHashSet;
import javautilSet;
import javaxpersistenceEntity;
import javaxpersistenceGeneratedValue;
import javaxpersistenceGenerationType;
import javaxpersistenceId;
import javaxpersistenceOneToMany;
import javaxpersistenceTable;
/**
*
* @author hadeslee
*/
@Entity
@Table(name = JPADepartment)
public class Department implements Serializable {
private static final long serialVersionUID = L;
@Id
@GeneratedValue(strategy = GenerationTypeAUTO)
private Long id;
@OneToMany(mappedBy = department)
private Set<Person> persons = new HashSet<Person>();
private String deptName;
private String description;
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
thisdeptName = deptName;
}
public String getDescription() {
return description;
}
[] [] [] [] []