Spring Data - ignore parameter if it has a null value

前端 未结 9 1536
暖寄归人
暖寄归人 2020-11-29 03:59

I want to have a spring data repository interface that takes two parameters. Is there a way to make it have the following behaviour?

MyObject findByParameter         


        
9条回答
  •  眼角桃花
    2020-11-29 04:24

    One solution that's missing here is Spring Data JPA's Query By Example feature and leverage the ExampleMatcher#ignoreNullValues, which is built exactly to solve this problem. A custom query and query builder are not necessary.

    This Spring Data query:

    ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
    Example exampleQuery = Example.of(new MyObject("foo", null), matcher);
    List results = repository.findAll(exampleQuery);
    

    Yields a query that looks like:

    select * 
    from myObject 
    where parameter1 = "foo"
    

    While the following:

    ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
    Example exampleQuery = Example.of(new MyObject("foo", "bar"), matcher);
    List results = repository.findAll(exampleQuery);
    

    Yields:

    select * 
    from myObject 
    where parameter1 = "foo"
    and parameter2 = "bar"
    

    Very cool!

    Note: One thing you'll have to do to your Repository interface is add the QueryByExample interface. You can do this either by extending the QueryByExample interface directly, or implicity via the JpaRepository:

    public interface MyObjectRepository extends JpaRepository {}
    

提交回复
热议问题