Hibernate generic type handling

23 views Asked by At

I have an Entity class which has a generic type field. I want this class to be saved and read from the database. Hibernate can't just take that generic type and save/read it, which is why it asks for custom @Type handling. Therefore it expects a Class<? extends UserType<?>>. I have been struggling to figure how to properly implement that class. (And I don't know if what I'm trying to do is even possible :D) Does anyone know how to deal with this?

Entity:

@Entity
@Table(name = "my_table")
public class MyEntity<T extends Serializable> implements Serializable {

    @Id
    @Column(name = "id", length = 128)
    private String id;

    // @Type(MyEntityType.class)
    @Column(name = "value")
    private T value;

}

Error: Property 'my.package.entity.MyEntity.value' has an unbound type and no explicit target entity (resolve this generics usage issue or set an explicit target attribute with '@OneToMany(target=)' or use an explicit '@Type')

1

There are 1 answers

0
Malvin Lok On

Maybe you can try something like:

@Entity
@Table(name = "my_table")
public class MyEntity<T extends Serializable> implements Serializable {

    @Id
    @Column(name = "id", length = 128)
    private String id;

    @Type(type = "my.package.GeneralizedUserType")
    @Column(name = "value")
    private T value;

}
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.*;

public class GeneralizedUserType implements UserType {

    @Override
    public int[] sqlTypes() {
        return new int[] {Types.JAVA_OBJECT};
    }

    @Override
    public Class<Serializable> returnedClass() {
        return Serializable.class;
    }

    //...
}