i have the following classes:
//Product class
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
//Package Class
public class Package {
@Id
@GeneratedValue
private Long id;
@OneToOne(cascade=CascadeType.ALL)
private Product product;
private int quantity;
private char mode;
private String unity;
private String description;
@OneToOne(cascade=CascadeType.ALL)
private Usuario user;
public class User {
@Id
private String email;
I can insert a product, an user and a package just doing:
//.. (iniatilize product and user before and set in package object)
session.save(package);
session.getTransaction().commit();
So why i can’t delete an user ?
User user = new User();
user.setEmail("valter@gmail.com");
session.delete(user);
session.getTransaction().commit();
Gives me this error :
Cannot delete or update a parent row:
a foreign key constraint fails
What’s wrong with my classes ?
Complete Entity User
@Entity
public class Usuario {
@Id
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@Entity
public class Package{
@Id
@GeneratedValue
private Long id;
@OneToOne(cascade=CascadeType.ALL)
private Product product;
private int quantity;
private char mode;
private String unity;
private String description;
@OneToOne(cascade=CascadeType.ALL)
private User user;
@Entity
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
That’s all entities envolved in the system.
@Bozho Based in what you say , it should be this way right?
@Entity
public class User{
@Id
private String email;
@OneToOne(cascade=CascadeType.ALL)
private List<Package> packages;
I’m trying to execute this method:
private static void deleteUser() {
Session session = new HibernateUtil().getSession();
session.beginTransaction();
try{
User usuario = (Usuario) session.load(Usuario.class, "valter@gmail.com");
session.delete(usuario);
session.getTransaction().commit();
}catch(HibernateException he){
session.getTransaction().rollback();
}finally{
session.close();
}
}
It appears you are creating a detached entity and trying to delete it, rather than fetching a complete entity from the DB. In this case, even if you have cascades defined, they won’t work because and relationship of the
Userentity is not populated.If the email is the primary key, then you should do the following:
Even with that, if any other entity references a
User, it will logically fail – the just look at the database constraints. You have multiple ways to fix this:List<Package>in your user, thus making the relationship bi-directional. Thus you’ll be able to set the cascade on theUserside as wellDELETE FROM Package WHERE user=:user".