Search code examples
javaspringsearchspring-data-jpajpql

Search with Spring Data JPA


I have a domain object Item: Item fields: a, b, c It has a lot more fields in reality.

I know I can create methods like:

  • findByAAndB(...)

  • Use @Query(SELECT ... WHERE ...) on my custom find method

But I still wonder if there is a better solution: What is the easiest to query the items table given that I may have a bunch of fields to query for at the same time?

If I have a method as shown below, is there a way that automatically maps the fields that are say != null into a SELECT?

  • findBy(Item prototype)

Solution

  •  public class Item{
          String a,b,c;
        }
    
    
        Item item=new Item();
        item.setA("a");
        Example<Item> itemExample=ExampleOf(item);
        List<Item> res=itemRepository.findAll(example);
    

    Source: Query By Example