Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed generic field using Hibernate?

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?

like image 689
Kao Avatar asked Oct 19 '22 16:10

Kao


1 Answers

Hibernate cannot persist generic fields due to Type Erasure.

However, I've managed to find a simple workaround:

  1. Add @Access(AccessType.FIELD) annotation to the class.

  2. Add @Transient annotation to field you want to persist.

  3. Create a specific getter and setter which uses this field.

  4. Add @Access(AccessType.PROPERTY) to the getter.

  5. 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 {

...
like image 174
Kao Avatar answered Oct 29 '22 02:10

Kao