使用注释休眠一对多删除

使用注释休眠一对多删除

本文介绍了使用注释休眠一对多删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在休眠时删除OneToMany和ManyToOne时遇到问题。我想问题是我有一个孩子的父母。这是我如何得到的。

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

正如您所看到的,person(persona)与角色(rol)和国家(pais)。
我的实体是这样的:

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(国家)

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(角色)

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;
    }

我试图删除Person并且只有这个人,所以我认为我必须首先将国家和角色分开,然后删除该人员,但这不起作用。这是我删除的代码

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

希望你能帮助我,这个在hibernate中删除的东西吓到我了。

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

推荐答案

如果你只是想删除Person。您可以删除它。

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

这篇关于使用注释休眠一对多删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:42