Query By Example method
I think the best option for you is to use the (imo, somewhat infrequently used) QueryByExample
feature of Spring Data JPA. On researching this answer, I posted an answer somewhere else that needed the same response. I'd take a look at that to get an idea of how this solves your problem.
You'll first need to the QueryByExampleExecutor
to your Repository
.
Secondly you'll just need to create your query like so (and hopefully you're using fluent builders for your entities!):
ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
Example<MyObject> exampleQuery = Example.of(new MyObject()
.withEntity1(new Entity1().withName("foo"), matcher);
repository.findAll(exampleQuery);
Would select all of the MyObject
elements with Entity1
having name
of foo
.
ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
Example<MyObject> exampleQuery = Example.of(new MyObject()
.withEntity1(new Entity1().withName("foo"),
.withEntity2(new Entity2().withName("bar"),
.withEntity3(new Entity3().withName("baz"),
.withEntity4(new Entity4().withName("foo"),
.withEntity5(new Entity5().withName("bar"),
.withEntity6(new Entity6().withName("baz"),
.withEntity7(new Entity7().withName("foo")
), matcher);
repository.findAll(exampleQuery);
Would select all of the MyObject
elements for Entity1
with name
of foo
, Entity2
, with name
of bar
, etc.