Asked the delete operation problem of a hibernate


The two table, structure and content are as follows:

The User table
------
ID name company_id -- a field name
1 u1 1
2 u2 1

The Company table
---------
ID name -- a field name
1 HTC



The idea:
----
The User table and the Company table is a many to one relationship. My idea is to remove the Company, a record in the table, the records of all the records associated with the User table are deleted.



The main executable code:
----------
Company c = (Company) session.load(Company.class, 1);
session.delete(c);



Error message:
-------
org.hibernate.exception.ConstraintViolationException: could not execute statement
at

...............
...............
...............

Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`hibernate`.`user`, CONSTRAINT `FK_7ek00pkat74ouxb736anasf9e` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`))
...............
...............
...............






With User.java and Company.java source code

@Entity
public class Company {

private int id;
private String name;
private Set<User> user = new HashSet<User>();

@OneToMany(cascade={CascadeType.ALL},mappedBy="company")
public Set<User> getUser() {
return user;
}
public void setUser(Set<User> user) {
this.user = user;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

@Entity
public class User {
private int id;
private String name;
private Company company;

@ManyToOne
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}

@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

cascade={CascadeType.ALL}Regardless of the setting in which one party, it doesn't matter..... There will be delete error... And great advice.......... Thank!!!!!!!!!!

Started by Jenny at November 16, 2016 - 1:04 PM

In the CascadeType.ALL and a set none and then the foreign key column in the database is set to allow for null.

Posted by Fabian at November 25, 2016 - 1:55 PM

Your hibernate mapping file.

Posted by Jerome at November 26, 2016 - 2:41 PM