spring-boothibernatejpanaturalid

How to fetch multiple entities by a list of natural ids with Hiberate or JPA repository?


If I have a list of natural Ids, how can I fetch all the records in the DB associated with these natural Ids at once?

All I've seen are methods that let you find an entity by a natural Id, an example of one is shown below.

    @Override
    public Optional<T> findBySimpleNaturalId(ID naturalId) {

        Optional<T> entity = entityManager.unwrap(Session.class)
                .bySimpleNaturalId(this.getDomainClass())
                .loadOptional(naturalId);

        return entity;
    }

I am looking for a method that can take a list natural Ids and fetch all the entities with these natural Ids. My current Entity has a autogenerated UUID and a naturalId and I'd like to keep it this way.

Is there something like this below

List<Song> songs = entityManager
.unwrap(Session.class)
.byMultipleSimpleNaturalIds(Song.class)
.multiLoad(songGroup.getSongIds());

// or using the repository
customRepository.findAllByNaturalId(...)

Solution

  • The examples you've seen are showing you how to build them yourself, as spring does not provide individual methods for you; it knows nothing about properties in your entity other than it must have an id. If you want a findAllByNaturalId method, you have to define it in the interface.

    Specifying this in your customRepository:

    public List<Song> findByNaturalIdIn(List<Int> naturalIds);
    

    Spring should generate an implementation that creates a query similar to "Select s from Song s where s.naturalId In :naturalIds".

    If it doesn't, just add that JPQL query string as an annotation and it will execute it for you:

    @Query(value = "Select s from Song s where s.naturalId In :naturalIds")
    public List<Song> findByNaturalIdIn(List<Int> naturalIds);
    

    Or you can write your own implementation method to execute your loadOptional calls, or any query you wish, but you still must define the method in your repository.