如何使用 Hibernate 嵌入通用字段?

How to embed generic field using Hibernate?

是否可以使用 Hibernate 嵌入通用字段?

我试图通过以下方式做到这一点:

@Entity
public class Element<T> {

    @Embedded
    private T value;
...

但我有:

 org.hibernate.AnnotationException: 
 Property value has an unbound type and no explicit target entity.

我知道 value 的目标类型将是 SpecificValue 类型。但是如何指定呢?

由于 Type Erasure,Hibernate 无法保留通用字段。

不过,我设法找到了一个简单的解决方法:

  1. @Access(AccessType.FIELD) 注释添加到 class。

  2. 向要保留的字段添加 @Transient 注释。

  3. 创建一个 specific getter 和 setter 使用此字段。

  4. @Access(AccessType.PROPERTY) 添加到 getter。

  5. 通过将 @Embeddable 属性 添加到 class 使字段类型可嵌入。

通过这种方式,您将能够嵌入特定类型的 属性。

这是修改后的代码:

@Entity
@Access(AccessType.FIELD)
public class Element<T> {

   @Transient
   private T value;

   @Access(AccessType.PROPERTY)
   private SpecificValue getValue() {
       return (SpecificValue) value;
   }

   private void setValue(SpecificValue v) {
       this.value = (T) v;
   }

...

@Embeddable
public class SpecificValue {

...