Hibernate one-to-many deleting with annotations

2019-08-05 04:15发布

问题:

I have a problem with deleting OneToMany and ManyToOne on hibernate. I guess the problem is that I have two parents for a single child. This is how I got it

Persona        Rol        Pais
 id             id         id
 name           name       name
 Pais
 Rol

As you can see, the person (persona) is related to the role (rol) and the country (pais). My entities are like this:

Person

public class Persona  implements java.io.Serializable {
  @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="Pais", nullable=false)
    public Pais getPais() {
       return this.pais;
    }

@ManyToOne(fetch=FetchType.LAZY)
   @JoinColumn(name="Rol", nullable=false)
   public Rol getRol() {
      return this.rol;
   }

Pais (Country)

public class Pais  implements java.io.Serializable {
   private Set<Persona> personas = new HashSet<Persona>(0);
   @OneToMany(fetch=FetchType.LAZY, mappedBy="pais", cascade=CascadeType.ALL,orphanRemoval=true)
  public Set<Persona> getPersonas() {
    return this.personas;

Rol (role)

public class Rol  implements java.io.Serializable {
  private Set<Persona> personas = new HashSet<Persona>(0);

  @OneToMany(fetch=FetchType.LAZY, mappedBy="rol", cascade=CascadeType.ALL,orphanRemoval=true)
    public Set<Persona> getPersonas() {
      return this.personas;
    }

I'm trying to delete the Person and only the person so I think that I have to detach the country and the role first and then delete the person but that doesn't work. This is my code for deleting

session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Persona p = (Persona)session.load(Persona.class, idPersona);
Pais pais = (Pais)session.load(Pais.class, p.getPais().getId()); //try to p.getPais();
rol rol = (Rol)session.load(Rol.class,p.getRol().getId()); //try to p.getRol();
pais.getPersonas().remove(p);
rol.getPersonas().remove(p);
p.setPais(null);
p.setRol(null);
session.update(pais);
session.update(rol);
session.delete(p);
session.getTransaction().commit();
session.close();

Hope you can help me, this deleting thing in hibernate is freaking me out.

回答1:

If you just want to delete Person. You can just delete it.

session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Persona p = (Persona)session.load(Persona.class, idPersona);
session.delete(p);
session.getTransaction().commit();
session.close();