示例查询方法
我认为对您来说最好的选择是使用 Spring Data JPA 的(imo,有点不常用)QueryByExample 功能。在研究这个答案时,I posted an answer somewhere else 需要相同的响应。我会看一下,以了解这如何解决您的问题。
您首先需要将QueryByExampleExecutor 转至您的Repository。
其次,您只需要像这样创建您的查询(希望您为您的实体使用fluent builders!):
ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
Example<MyObject> exampleQuery = Example.of(new MyObject()
.withEntity1(new Entity1().withName("foo"), matcher);
repository.findAll(exampleQuery);
将选择所有MyObject 元素,其中Entity1 具有name 的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);
将为Entity1 和name 的foo、Entity2、name 的bar 等选择所有MyObject 元素。