[英]Spring Data JPA apply sorting, pagination along with a where clause
I am currently Using Spring JPA and utilizing the Sorting and Pagination as described here - 我目前正在使用Spring JPA并使用此处所述的排序和分页 -
How to query data via Spring data JPA by sort and pageable both out of box? 如何通过Spring数据JPA通过排序和分页来查询数据?
Now my question is how do I apply a 'where' clause to this? 现在我的问题是如何在这里应用'where'子句?
Eg 例如
where PRODUCT_NAME='abc';
Just create a query method in your repository interface for this. 只需在存储库界面中创建一个查询方法即可。
Take a look in the docs, here . 在这里看看文档。
Add a query method with paging and where clause. 使用paging和where子句添加查询方法。
Page<User> findByLastname(String lastname, Pageable pageable);
So you can find User by a property "lastname" and configure Paging settings. 因此,您可以通过属性“lastname”找到User并配置分页设置。
The easiest way I could find is to use QueryDSL or Specifications . 我能找到的最简单的方法是使用QueryDSL或规范 。 I prefer QueryDSL. 我更喜欢QueryDSL。
To fetch Spring Data JPA apply sorting, pagination along with a where clause check bellow codes 要获取Spring Data JPA应用排序,分页以及where子句检查下面的代码
Entity class 实体类
@Entity @Table(name = "users") Public Class User{ private String name; private Integer id; private String email; // add required setter getter// }
Repository class 存储库类
@Repository("userRepository") @Transactional` public interface UserRepository extends JpaRepository<User, Integer>{ }
Service layer to pass where clause using Example object and Pagination+Sorting together using Pagable and Sort Class. 服务层使用Example对象传递where子句,并使用Pagable和Sort Class将Pagination + Sorting一起传递。 We will implement Pageable in controller to inject Sorting logic then will pass that Pagable object to service Layer. 我们将在控制器中实现Pageable以注入排序逻辑,然后将该Pagable对象传递给服务层。
@Service Public class UserService{ public Page<User> getUserListPaginated(`EXAMPLE<User>` searchTerm, Pageable pageable) { return userRepo.findAll(searchTerm,pageable); } }
Example<T>
does not take the attribute if its value is null. Example<T>
如果其值为null,则不接受该属性。 for that I used Integer id in Entity class as I can set it's value null for first call 因为我在Entity类中使用了Integer id,因为我可以为第一次调用设置它的值null
Now Controller Class 现在控制器类
@Controller Public class UserController{ @Autowired UserService userService; @GetMapping("/users") public String users(Model model,@RequestParam(value="page",defaultValue = "0") Integer pageNumber, @SortDefault(sort = "name", direction = Sort.Direction.ASC) Sort sort){ Pageable pageable = PageRequest.of(pageNumber,10, sort); Example<User> searchTerm = Example.of(new User()); Page<User> userList = userService.getUserListPaginated(searchTerm, pageable); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.