Is it possible to embed generic field using Hibernate?
I tried to do this in a following way:
@Entity
public class Element<T> {
@Embedded
private T value;
...
But I've got:
org.hibernate.AnnotationException:
Property value has an unbound type and no explicit target entity.
I know that the target type of value
will be a SpecificValue
type. But how to specify this?
Hibernate cannot persist generic fields due to Type Erasure.
However, I've managed to find a simple workaround:
Add @Access(AccessType.FIELD)
annotation to the class.
Add @Transient
annotation to field you want to persist.
Create a specific getter and setter which uses this field.
Add @Access(AccessType.PROPERTY)
to the getter.
Make the type of the field embeddable by adding @Embeddable
property to the class.
In this way you will be able to have an embedded property of specific type.
Here is a modified code:
@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 {
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With