用Hibernate JPA处理超类和子类 [英] handling superclasses and subclasses with Hibernate JPA

查看:210
本文介绍了用Hibernate JPA处理超类和子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这些对象已经有了一个类型层次结构,并且我试图让它和hibernate一起工作。



CatalogPackage对象具有所有重要属性和所有getter。 CatalogPackageImpl(扩展CatalogPackage)对象没有属性,但是大多数setter。

  @Entity 
@Table name =package)
public class CatalogPackage {

protected String mId;

public String getId(){return mId;}
}

public class CatalogPackageImpl extends CatalogPackage {

public void setId(String id){
mId = id;
}
}

我不知道为什么要设置这个。它应该提供类似于界面的设置,因此客户端无法修改字段。



我们希望代码引用CatalogPackage对象。但是当试图持久化一个CatalogPackages数组(实际上是CatalogPackageImpls)时,hibernate会这样说:

catalog.internal.CatalogPackageImpl



如何建议hibernate在持久化对象时使用超类?

我并不想将所有setter移动到超类,我绝对不希望使用CatalogPackageImpl作为实体。

解决方案这可以起作用,除了让 CatalogPackageImpl 一个实体或另一个实体:

  @MappedSuperclass 
public class CatalogPackage {
protected String mId;
public String getId(){return mId;}
}

@Entity
@Table(name =package)
public class CatalogPackageImpl extends CatalogPackage {
public void setId(String id){
mId = id;
}
}


I am trying to persist objects in a database using hibernate JPA.

The objects already have a type hierarchy, and I'm trying to make it work with hibernate.

A CatalogPackage object has all the important properties and all the getters. A CatalogPackageImpl (extends CatalogPackage) object has no properties, but most of the setters.

@Entity
@Table(name="package")
public class CatalogPackage {

    protected String mId;

    public String getId() {return mId;}
}

public class CatalogPackageImpl extends CatalogPackage {

   public void setId(String id) {
      mId=id;
   }
}

I've no idea why things are set up like this. It's supposed to provide an interface-like setup, so clients can't modify fields.

We want code to refer to CatalogPackage objects. But when trying to persist an array of CatalogPackages (which are in fact CatalogPackageImpls underneath), hibernate says this:

java.lang.IllegalArgumentException: Unknown entity: com.mycompany.catalog.internal.CatalogPackageImpl

How do I suggest to hibernate that it use the superclass when persisting the objects?

I don't really want to move all the setters to the superclass, and I definitely don't want to use CatalogPackageImpl as the entity.

解决方案

This would work, there is really no other way than to make CatalogPackageImpl an entity one way or the other:

@MappedSuperclass
public class CatalogPackage {
    protected String mId;
    public String getId() {return mId;}
}

@Entity
@Table(name="package")
public class CatalogPackageImpl extends CatalogPackage {
   public void setId(String id) {
      mId=id;
   }
}

这篇关于用Hibernate JPA处理超类和子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆