This is due to the way JPA specifies EntityManager.getReference(…)
to work. It's supposed to return a proxy that will either resolve the object to be returned on the first access of a property or throw the contained exception eventually.
The easiest way to work around this is to simply use findOne(…)
instead, like this Optional.ofNullable(repository.findOne(…))
. findOne(…)
will return null
in case no result is found.
A more advanced way of resolving this is to make the repository return Optional
instances directly. This can be achieved by creating a custom base repository interface using Optional<T>
as return type for the find…
-methods.
interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
Optional<T> findOne(ID id);
// declare additional methods if needed
}
interface YourRepository extends BaseRepository<DomainClass, Long> { … }
Find a complete example of this in the Spring Data examples repository.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…