jakartaee / jakartaee/persistence
Support for loading by natural-id
- Dominant language
- Java
- Stars
- 268
- Forks
- 78
- Avg merge
- 1d 6h
- Merged PRs (30d)
- 13
Description
I propose the spec adds the ability to load by an entity's natural-id, if it has one.
In terms of the actual load, this could be handled by a Query ofc. What is interesting in this API though is that it can make efficient use of both the EntityManage caches as well as the "second level" cache. In other words it can be much more efficient. Similar to loading by id.
It would center around a new `@NaturalId` annotation which you would place on the attribute(s) making up the entity's natural-id[1]:
```java
@Entity
class Product {
@Id Integer id;
@NaturalId String sku;
...
}
```
And then an API to load-by-natural-id. This is how I defined the API in Hibernate (pseudo). I know the exact API will not be everyone's cup-of-tea, but for now I am just proposing the concept.
```java
EntityManager em = ...;
Session session = em.unwrap( Session.class );
Product product = em.unwrap( Session.class )
.byNaturalId( Product.class )
.find( "123-45678" );
```
I chose that paradigm to avoid overloads for every conceivable options. JPA API prefers the overloads, so a more "JPA-y" API might be:
```java
EntityManager em = ...;
Product product = em.loadByNaturalId( Product.class, "123-45678" );
```
Along with overloads for any options we want to allow.
Personally I'd say to restrict this to just basic and embeddable types. When doing this in Hibernate I also added the ability to annotate multiple attributes which indicates a "decomposed" composition. In retrospect I now think that was a mistake.
In Hibernate, we also added `@NaturalIdCache` to control whether we should cache at the "second level".
Contributor guide
Research direction
Start by reviewing the existing EntityManager API and the proposed @NaturalId annotation and load-by-natural-id entry points described here. The issue needs an agreed specification for natural-id mapping, loading behavior, and cache interaction before implementation can be considered done.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- api, database
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100