是否可以使用Hibernate嵌入泛型字段?
我尝试以下列方式执行此操作:
@Entity
public class Element<T> {
@Embedded
private T value;
...
但我有:
org.hibernate.AnnotationException:
Property value has an unbound type and no explicit target entity.
我知道目标类型的值将是一个SpecificValue类型.但是如何指定呢?
最佳答案 由于
Type Erasure,Hibernate无法保留通用字段.
但是,我设法找到了一个简单的解决方法:
>将@Access(AccessType.FIELD)注释添加到类中.
>将@Transient注释添加到要保留的字段中.
>创建使用此字段的特定getter和setter.
>将@Access(AccessType.PROPERTY)添加到getter.
>通过将@Embeddable属性添加到类中,使字段的类型可嵌入.
通过这种方式,您将能够拥有特定类型的嵌入属性.
这是一个修改过的代码:
@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 {
...