简体   繁体   English

使用Hibernate JPA处理超类和子类

[英]handling superclasses and subclasses with Hibernate JPA

I am trying to persist objects in a database using hibernate JPA. 我正在尝试使用休眠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. CatalogPackage对象具有所有重要的属性和所有的吸气剂。 A CatalogPackageImpl (extends CatalogPackage) object has no properties, but most of the setters. CatalogPackageImpl(扩展CatalogPackage)对象没有属性,但是大多数设置器。

@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. 我们希望代码引用CatalogPackage对象。 But when trying to persist an array of CatalogPackages (which are in fact CatalogPackageImpls underneath), hibernate says this: 但是,当尝试持久保存一个CatalogPackages数组(实际上是下面的CatalogPackageImpls)时,hibernate这样说:

java.lang.IllegalArgumentException: Unknown entity: com.mycompany.catalog.internal.CatalogPackageImpl java.lang.IllegalArgumentException:未知实体: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. 我真的不想将所有的setter都移到超类中,并且我绝对不希望使用CatalogPackageImpl作为实体。

This would work, there is really no other way than to make CatalogPackageImpl an entity one way or the other: 这将起作用,实际上除了使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;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM