Felix Feisst
Felix Feisst

Reputation: 175

Hibernate query subtyped entity by natural-id

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.

Upvotes: 1

Views: 922

Answers (2)

Adrian
Adrian

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

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154200

  1. 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.

  2. 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.

  3. 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

Related Questions