我正在尝试查看如何创建JPA Critera查询,该查询允许使用多个级别进行完全动态过滤。
例如
select *
from table
where (
(column1 = 'A'
and
(column2 = 'B' or column3 = 'C')
)
or
column3 = 'D'
答案 0 :(得分:0)
您需要在下面的测试中创建规范。这可能是动态的。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=HelloWorldConfig.class)
public class SpecificationTest {
@Autowired
private AccountRepository repository;
@Test
public void test1() {
final List<String> names = Arrays.asList(new String[]{"George","Max"});
Specification<Account> specification = new Specification<Account>() {
public Predicate toPredicate(Root<Account> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(root.get("name").in(names).not());
return builder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
assertNotNull(repository);
repository.save(makeAccount("Greg", "123456787", "01-02-01"));
repository.save(makeAccount("George", "123456788", "01-02-02"));
repository.save(makeAccount("Max", "123456789", "01-02-03"));
List<Account> accounts = repository.findAll(specification);
assertEquals(1,accounts.size());
assertEquals("123456787",accounts.get(0).getAccountNumber());
}
private Account makeAccount(String name, String accountNumber, String sortCode) {
Account account = new Account();
account.setName(name);
account.setAccountNumber(accountNumber);
account.setSort(sortCode);
return account;
}
}
存储库的位置如下:
@Repository
public interface AccountRepository extends JpaRepository<Account, Long>, JpaSpecificationExecutor<Account> {
}