Reputation: 474
I've run into a problem and I don't know, if is possible to solve it. Let me show you my code and explain the situation. I have an abstract class User
mapped as superclass.
@MappedSuperclass
public abstract class User extends AbstractEntity {
}
Then I have two classes, Person
and Company
, extending the superclass.
@Entity
public class Person extends User {
}
@Entity
public class Company extends User {
}
Since this, everything is ok. I have two tables called by the entity names and it works june fine. But, I have some entity called Invoice
, where I have to map Person
or Company
into.
@Entity
public class Invoice extends AbstractEntity {
@ManyToOne()
@JoinColumn(name="user_id", updatable=false)
private Class<? extends User> user;
}
The problem is that I don't know, which implementation of User
will be mapped to this Invoice
entity. With this solution, Hibernate gives me an error org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.xxx.user references an unknown entity: java.lang.Class
I understand it, but please, is there any way to implement this behaviour without an exception ? Or am I completely wrong and nothing similar can be done in ORM ?
I cannot use private User user
because User
is a @MappedSuperclass
, not an @Entity
.
Thanks !
Upvotes: 2
Views: 1834
Reputation: 27000
Well instead of using lower bound, why not just use the type User
:
@Entity
public class Invoice extends AbstractEntity {
@ManyToOne()
@JoinColumn(name="user_id", updatable=false)
private User user;
}
Like this, you should still be able to put any class that extends from the User
class as the previous declaration. However this will not work as User
is not an Entity
.
It should however work, if you declare User
as entity but set inheritance strategy to TABLE_PER_CLASS
.
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class User extends AbstractEntity {
}
Upvotes: 2
Reputation: 7048
Hibernate won't see the generic "User" at runtime (type erasure).
Use User
instead of Class<? extends User>
Note that even if Hibernate could see the generic type, you'd still have a user Class
not a User
...
Upvotes: 0