Home > Software design >  How does Spring Data decide what is returned by FindBy
How does Spring Data decide what is returned by FindBy

Time:04-27

How does Spring Data's findBy decide which database record to return if there are multiple matches?

I realised if I have more than one entry in my Elastic Search database with the same attribute code (ie: "123"), Spring only returns one entry when I call a 'findByAttributeCode'.

If I use a findById, its self explanatory as Id's are unique, however with other findBys, there can be many matches. Note: attributeCode is NOT unique.

How does Spring decide which one to return?

My call would be something like this: Attribute attribute = findByAttribute(attributeCode);

The repo would look like this:

public interface AttributeRepository extends ElasticsearchRepository<Attribute, String> {
    
    Attribute findByAttributeCode(String attributeCode);
}

CodePudding user response:

What you should be doing, if there are more than one possibility is creating the method stub like this:

<Iterable>Attribute findByAttributeCode(String attributeCode);

This way you return them all. If you don't do that, you are beholden to the RDBMS in how it builds it swap to return a single entry from the multiple tuples it will return from the query it builds, which should be something like:

select * from table where attributeCode = ?;

CodePudding user response:

This is taken from the return type that you define for your function. If you specify a collection, all matching documents are returned for your query.

If you define a single object as return type, the first entry returned from the underlying store - here Elasticsearch - is returned. What this first entry is, depends on your query criteria, sort parameters - whatever Elasticsearch returns first, is returned to the caller.

  • Related