Enhance Spring Data JPA with Hibernate's Natural ID support for optimized entity lookups.
Natural IDs represent unique identifiers that naturally exist within your domain model. Unlike surrogate primary keys (typically generated IDs), natural IDs have business meaning.
Examples of Natural IDs:
- Tax identifier for a company
- ISBN for a book
- Email address for a user
- Social security number for a person
When using standard Spring Data JPA methods such as findByTaxIdentifier
or getByTaxIdentifier
, Spring Data will force Hibernate to perform a SQL query every time, ignoring Hibernate's session cache (and L2 cache).
This means that even if you've already loaded an entity by its natural ID, Spring Data will execute a new SQL query when you try to load it again.
This library automatically detects repository methods that query entities by their natural identifiers and redirects them to use Hibernate's Session.bySimpleNaturalId()
method, which:
- Checks the session cache first
- Uses optimized queries when going to the database
- Can leverage L2 cache if configured
Add the following dependency to your project:
<dependency>
<groupId>com.github.pocketcombats</groupId>
<artifactId>spring-data-naturalid</artifactId>
<version>1.3</version>
<scope>runtime</scope>
</dependency>
@Entity
public class Company {
@Id
private Integer id;
@NaturalId
private String taxIdentifier;
// Other fields, getters, setters...
}
public interface CompanyRepository extends Repository<Company, Integer> {
// Standard method to find by primary key
Optional<Company> findById(Integer id);
// Method to find by natural ID - will be optimized!
Optional<Company> findByTaxIdentifier(String taxIdentifier);
// Alternative semantic - also works
Company getByTaxIdentifier(String taxIdentifier);
}
The library will automatically detect your natural ID methods and optimize them. No additional configuration is needed.
If you want to enable L2 cache for natural IDs, annotate your entity with @NaturalIdCache
:
@Entity
@NaturalIdCache
public class Company {
@Id
private Integer id;
@NaturalId
private String taxIdentifier;
// ...
}
- Currently only supports entities with a single natural ID attribute
- Only works with simple natural IDs (not composite natural IDs)
- Only intercepts methods named
findByX
orgetByX
where X is the natural ID attribute name
This library uses Spring's BeanPostProcessor
to enhance repository beans. It:
- Detects repositories working with entities that have natural IDs
- Identifies methods that should use natural ID lookups (findByX, getByX)
- Intercepts these methods and redirects them to use Hibernate's natural ID API
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.