Reputation: 175
I use Hibernate and want to query for entities by their natural identifier. However, it seems not to be possible to have natural ids on subtypes. I have two classes A and B where B extends A:
class A {
long id;
}
class B extends A {
String naturalId;
}
A
is mapped in Hibernate with its own identifier. B
is mapped as joined subclass. However, it is not possible to map the natural identifier of B
in Hibernate because the mapping of B
is a subclass mapping.
Why is it not possible to have a natural identifier on the subclass B
? Note that I don't want Hibernate to generate my database schema, I just want to have natural ids for fast cache hits.
Is there a way/a best practice to have natural ids on subtypes for fast second level cache querying?
Upvotes: 1
Views: 922
Reputation: 3731
According to 13.3. Entity inheritance and second-level cache mapping:
As of Hibernate ORM 5.3, you can now override a base class @Cacheable or @Cache definition at subclass level.
so you might have a chance by resetting the caching annotations on B
.
I never tried it so please confirm the solution with a comment.
Upvotes: 0
Reputation: 154200
NaturalId only make sense for base classes, because you can't retrieve a sub-class without the base class info.
Let's say you could map map both the base class and the sub-class with a natural-id:
class A {
long id;
String baseId;
}
class B extends A {
String naturalId;
}
A a = session.bySimpleNaturalId( A.class ).load( "abc" );
If the entity we retrieve if of type B, it's not clear which of the natural-id variants will be used.
You can't fetch a sub-class without getting the base-class info. So when you load a Sub-class from cache, the associated base-class info is retrieved as well. Therefore you could have the base class store the natural-id, or simply use the primary key for caching.
You can update the natural-id, although a business key should be immutable. For mutable natural-ids you need to use the mutable attribute.
Upvotes: 1