I have this entity. It should work on both, internal and external, users.
@Entity(name = "TokenAuthentication")
class TokenAuthenticationEntity<T>(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null,
...
@NotNull
@ManyToOne(fetch = FetchType.EAGER)
val user: T,
) : BaseEntity()
When I run this, I get
Property TokenAuthenticationEntity.user has an unbound type and no explicit target entity. Resolve this Generic usage issue or set an explicit target attribute
So Hibernate tells me to f*** off with my generics, it needs explicit definitions. Any of you have an idea how to get this running with generics?
CodePudding user response:
This is not possible. The reason being T type erasure at compile-time. This T type is used at compile-time to check types and guarantee type safety, but then it is removed. Having said that, each instance of TokenAuthenticationEntity can have a different value for T, and as explained before this information is lost.
What you can actually do is the following:
@MappedSuperclass
public abstract class TokenAuthenticationEntity<T> {
private T user;
}
Now you can create your entities based on this generic superclass:
@Entity
public class InternalUser extends TokenAuthenticationEntity<IUser> { }
@Entity
public class ExternalUser extends TokenAuthenticationEntity<EUser> { }
Why? Because each concrete subclass of TokenAuthenticationEntity has a type T which is defined and is retained and unique inside the subclasses. In this case, JPA will store your subclasses in one or more tables, depending on the chosen @InheritanceStrategy
(if the Inheritance annotation is not specified or if no inheritance type is specified for an entity class hierarchy, the SINGLE_TABLE mapping strategy is used). Additional details at https://www.baeldung.com/hibernate-inheritance#single-table.