在java中,在使用泛型获得的类型上定义持久性版本属性是可行的吗?

时间:2015-08-21 11:04:30

标签: java generics jpa

也许这个问题本身并不是很清楚。我会解释一下。我有一些基本类来定义从它们扩展的实体,目的是避免重新编码总是相同的基本事物。在这种情况下,我有班级:

package libs.data.entities;

import java.io.Serializable;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class ExtendedEntity<ID extends Serializable, VERSION extends Number> extends SimpleEntity<ID>
{

    @Version
    @Basic(optional = false)
    @NotNull
    @Column(name = "CurVer", nullable = false)
    protected VERSION curVer;       // Current Version

    public ExtendedEntity()
    {
        id = null;
        curVer = null;
    }

    public VERSION getCurVer()
    {
        return curVer;
    }

    public void setCurVer(VERSION curVer)
    {
        this.curVer = curVer;
    }

}

在这个类中,ID和VERSION是我在定义实体类时可以设置的泛型类型。 @version注释警告我它不是版本属性的有效类型,但我认为如果使用Long类声明类Person,那么它应该可以工作。当我尝试在glassfish服务器(4.x)中启动Web应用程序时,它会生成错误:

Caused by: Exception [EclipseLink-7168] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The attribute [curVer] of type [class java.lang.String] on the entity class [class es.nextel.libs.data.entities.ExtendedEntity] is not valid for a version property. The following types are supported: int, Integer, short, Short, long, Long, Timestamp.
at org.eclipse.persistence.exceptions.ValidationException.invalidTypeForVersionAttribute(ValidationException.java:1153)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.VersionAccessor.process(VersionAccessor.java:122)
at org.eclipse.persistence.internal.jpa.metadata.MetadataDescriptor.processMappingAccessors(MetadataDescriptor.java:1536)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor.processMappingAccessors(ClassAccessor.java:1648)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.MappedSuperclassAccessor.processMetamodelDescriptor(MappedSuperclassAccessor.java:1219)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processStage2(MetadataProject.java:1784)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.processORMMetadata(MetadataProcessor.java:576)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:585)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1869)
... 62 more

提前谢谢你,对我的英语感到抱歉。

1 个答案:

答案 0 :(得分:0)

根据异常消息,您只能扩展VERSION的以下值,即int, Integer, short, Short, long, Long, Timestamp。因此,您无法在extends Number之后添加VERSION。你必须让它成为一个无类型的通用。您实现类必须确保它们使用其中一种有效类型。