2

Instead of specifying the field of an object that I want to search by in spring data, I want it to search by all of the fields. E.g.:

@Entity
@Table(name="FOO")
public class Foo{
private String firstName;
private String lastName;
private String middleName;
private String ssn;}

@Repository
public interface FooDao extends CrudRepository<Foo, Long>{
Foo findByFoo(Foo foo);}

Essentially what this does is look at the fields that are not null in a passed foo object and queries by them OR it queries all the fields the way they are, which can be null or not null.

Assume that Foo has a lot of fields and trying to write individual queries wouldn't be very elegant.

I also understand that I can dynamically do this myself, but I'd rather not do that if it's already possible.

1
  • Most JPA providers support a findByExample mechanism. I have a sample application that you can look at for creating your own JPA repository implementation that provides a findByExample of its own.
    – manish
    Commented Jul 21, 2015 at 8:41

2 Answers 2

2

Query by example is something not yet provided by Spring Data. However there's a rudimentary PR open for JPA and a more advanced feature branch available for Spring Data MongoDB. Please feel free to watch/vote for the related issues DATAJPA-218 and DATAMONGO-1245.

1

In the absence of QBE support, the next best solution would be to utilize the QueryDSL support offered by Spring Data. This would allow you to pass a Predicate based on any number of properties of Foo, therefore giving you similar functionality.

Your repository would then look like:

public interface FooRepository extends JpaRepository<Foo>, QueryDslPredicateExecutor {

}

The QueryDSL code generator plugin will generate a query object QFoo which you can use to build a Prediate to pass to the inherited findAll(Predicate predicate) method of your repository.

e.g.

BooleanBuilder builder = new BooleanBuilder(QFoo.firstName(eq("John"));
builder.and(QFoo.lastName(eq("John"));

Iterable<Foo> results = fooRepo.findAll(builder);

See here for further examples:

http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

http://docs.spring.io/spring-data/jdbc/docs/current/reference/html/core.querydsl.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.