JPA和hibernate对删除操作的不同
时间:2011-09-09 千里冰封
在hibernate里面调用session的delete方法以后,无论这个被删除的对象有 没有被人外键引用到,都可以被删除,并且此时的外键设为null,也就是说他会 自动帮我们去查看他被谁引用到了。然后把引用全部去掉后,再把自己删掉。而 在JPA里面,如果调用EntityManager.remove方法时,传进去的对象,有被外键 引用到,则会失败。因为JPA里面的实现就是直接执行delete语句,也不管他有 没有被外键引用,此时,当然会出错了。
测试时候使用的两个类分别如下:
举的例子是部门和员工的关系。一个部门可以有多个员工。然后把部门删掉 的时候,员工的部门属性就为null了,不过,按照严谨来说,还是JPA的严谨一 些。这样可以防止误操作,呵呵。
部门的实体对象
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.hadeslee.jpaentity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author hadeslee
*/
@Entity
@Table(name = "JPADepartment")
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
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) {
this.deptName = deptName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Person> getPersons() {
return persons;
}
public void setPersons(Set<Person> persons) {
this.persons = persons;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won''t work in the case the id fields are not set
if (!(object instanceof Department)) {
return false;
}
Department other = (Department) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.hadeslee.jpaentity.Department[id=" + id + "]";
}
}
JPA和hibernate对删除操作的不同(2)
时间:2011-09-09 千里冰封
人员的实体对象
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.hadeslee.jpaentity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import jav
|