Hibernate:当我尝试删除一个对象时,org.hibernate.WrongClassException

时间:2014-05-07 21:58:23

标签: java hibernate jpa

我正在使用继承来使用hibernate在JPA上描述我的模型,我有这个类:

@Entity
@Table(name = "evento")
@Inheritance(strategy = InheritanceType.JOINED)
public class Evento implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    @Id
    private int id;
    @Column(name = "numero")
    private String numeroEvento;

这个孩子班:

@Entity
@Table(name = "evento_sesion")
@PrimaryKeyJoinColumn(name = "idevento", referencedColumnName = "id")
public class EventoSesion extends Evento implements Serializable {

    @Column(name = "objeto")
    private String objeto;
...

问题是当我尝试执行“eventoFacade.remove(e)”(e是DB中现有对象的实例)时出现此错误:

Caused by: javax.persistence.PersistenceException: org.hibernate.WrongClassException: Object with id: null was not of the specified subclass: entidades.Evento (class of the given object did not match class of persistent copy)

有人可以帮助我或给我一些线索吗?

谢谢:)

1 个答案:

答案 0 :(得分:1)

我试着回答,但答案是推测性的;问题在于在实体管理器上执行remove的代码,即在eventoFacade.remove(e)中。

但是,假设您已在数据库中创建并存储了类型为EventoSession的实体,然后您尝试使用基类型的实例调用em.remove,那么您将获得异常你提到过。

让我们假设,类型EventoSession的实体具有主键1,现在我们尝试删除此实体。

Evento es = new Evento();
es.setNumeroEvento("...");
es.setId(1);

es = em.merge(es); // detached objects cannot be removed, therefore we merge es
em.remove(es);

em.merge的来电将以javax.persistence.PersistenceException结尾,原因是:

Caused by: org.hibernate.WrongClassException: 
    Object [id=null] was not of the specified subclass [entidades.Evento]: 
    class of the given object did not match class of persistent copy

我认为这可能是问题所在。

要修复它,只需通过实体管理器加载要删除的实例:

em.remove(em.find(Evento.class, 1));