Hibernate one-to-many deleting with annotations

自作多情 提交于 2019-12-11 09:30:16

问题


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();


来源:https://stackoverflow.com/questions/10437522/hibernate-one-to-many-deleting-with-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!