我这里有一个产品表的案例,需要通过用户输入(例如类别,颜色,大小,价格范围等)进行过滤。
我正在使用Spring Data JPA,并且对方法名称中的派生查询感到满意,当我被迫使用时,我只是对复杂的查询(例如联接和…)使用@query选项。
但是对于我需要的Filter方法,我恐怕不得不写这样的东西
> public interface ProductRepository extends JpaRepository<Product, Long> > { > //..... other methods > > Page<Product> > findByCategoriesContainingAndSalepriceBetween(List<Category> categories, > Float minprice, Float maxprice, PageRequest pagerequest); > > Page<Product> findByCategoriesContaining(List<Category> categories, > PageRequest pagerequest); > > Page<Product> findByCategoriesContainingAndSizeIn(List<Category> > categories,Int[] sizes, PageRequest pagerequest); > > Page<Product> > findByCategoriesContainingAndSizeInAndSalepriceBetween(List<Category> > categories,Float minprice, Float maxprice, PageRequest pagerequest); > }
所以我看过QueryDsl和Specification,但它们似乎有很多多余的代码,您能把我放在正确的道路上吗?
我不同意QueryDSL会导致大量额外的代码。这是QueryDSL的一些测试代码:
仓库定义:
public interface UserRepository extends PagingAndSortingRepository<User, Long>, QueryDslPredicateExecutor<User> { public User findOne(Predicate predicate); public List<User> findAll(Predicate predicate); }
基于各种属性及其组合的测试代码:
@Test public void testFindByEmailAddress() { User user = repository.findOne(QUser.user.emailAddress.eq("jack@hamilton.net")); Assert.assertNotNull(user); Assert.assertEquals("Jack", user.getForename()); Assert.assertEquals("Hamilton", user.getSurname()); } @Test public void testFindByGender() { List<User> users = repository.findAll(QUser.user.gender.eq(Gender.M)); Assert.assertEquals(4, users.size()); users = repository.findAll(QUser.user.gender.eq(Gender.F)); Assert.assertEquals(2, users.size()); } @Test public void testFindByCity() { List<User> users = repository.findAll(QUser.user.address.town.eq("Edinburgh")); Assert.assertEquals(2, users.size()); users = repository.findAll(QUser.user.address.town.eq("Stirling")); Assert.assertEquals(1, users.size()); } @Test public void testFindByGenderAndCity() { List<User> users = repository.findAll(QUser.user.address.town.eq("Glasgow").and(QUser.user.gender.eq(Gender.M))); Assert.assertEquals(2, users.size()); users = repository.findAll(QUser.user.address.town.eq("Glasgow").and(QUser.user.gender.eq(Gender.F))); Assert.assertEquals(1, users.size()); }