After calling the session's Delete method inside the hibernate, the deleted object can be deleted, regardless of whether it is referenced by a foreign key, and the foreign key at this time is set to NULL, which means that he will automatically help us to see who has been quoted by someone. Then remove all the references and delete them. In JPA, if the Entitymanager.remove method is invoked, the object passed in is referenced by a foreign key, and it fails. Because the implementation in JPA is to execute the DELETE statement directly, and whether or not he has been referenced by a foreign key, there is of course an error.
The two classes used at the time of the test were as follows:
The example is the relationship between the department and the staff. A department can have more than one employee. Then when the department is deleted, the employee's departmental attributes are null, but, in strict terms, the JPA is more rigorous. This can prevent misoperation, hehe.
Entity objects for the Department
/*
* 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 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 + "]";
}
}