Natural Id 2nd level Cache not working when Identity is database generated

Description

When an entity has a database generated identity and an immutable natural identity, identity values are supposed to be cached in second level cache when configured.
There seems to be a bug in public void org.hibernate.action.internal.AbstractEntityInsertAction.handleNaturalIdPostSaveNotifications(Serializable generatedId) method.
It receives a valid generated Id value, but disregards it when calling PersistenceContext$NaturalIdHelper.manageSharedNaturalIdCrossReference(...). It passes getId() method result which evaluates to null.
This causes null id value to be cached against the natural id value.
Then, every time the entity is looked up by the natural id value, cache returns null. Identity is looked up in the database, but not cached, because cache access strategy (ReadWriteEhcacheNaturalIdRegionAccessStrategy) never updates cache entries (they supposed to immutable).
In our system these lookups increase the database load dramatically.

Environment

Hibernate 4.3, 5.0 and 5.1
MS SQL Server and HSQL DB

Status

Assignee

Vlad Mihalcea

Reporter

Andrey Zavodnik

Fix versions

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Components

Affects versions

4.3.7
5.0.2
4.2.21
5.1.0

Priority

Major
Configure