Typesafe Primary Key in Hibernate/JPA
I am looking for a way to have a typesafe primary key for my entities using generics in Hibernate. Instead of doing this
@Entity
public class User{
@PrimaryKey
Long id
}
I was thinking of doing this...
@Entity
public class User{
@PrimaryKey
PrimaryKey<User,Long> id
}
Or take t开发者_StackOverflowhe type inference even further...
Any ideas? Has anybody ever tried this before? Would you do this by making your class PrimaryKey embeddable?
@Entity
public class User extends MyEntity<Long>//Primary key type{
@PrimaryKey
PrimaryKey<User> id;
}
While it is possible to use a PK class and to use it as a member of entities with the @EmbeddedId
, this would typically make all your JQL queries and your Java code more verbose:
select a.addressKey.id from Address a
or
AddressKey addressKey = new AddressKey();
addressKey.setCountry("USA");
addressKey.setId(634);
Address a = entityManager.find(Address.class, addressKey);
So I would personally use this for a real composite key (i.e. not with a single attribute) only.
Actually, I'm really wondering what problem you are trying to solve because at the end, you will have to deal with a Long
anyway. I don't really see the added value of a single attribute typesafe primary key.
If you are looking for a typesafe way to identify an entity, what about using its LazyLoadingProxy?
精彩评论