第五天

(一)Spring Data JPA 深入学习

  1. 自定义查询方法高级应用
    除了基本的命名规则查询,我还学习了如何利用分页和排序功能。在 Repository 接口中,通过在方法参数里添加 Pageable 或 Sort 对象,就能轻松实现分页查询和结果排序。例如:
    java
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.jpa.repository.JpaRepository;

import com.example.entity.User;

public interface UserRepository extends JpaRepository<User, Long> {
Page findByAgeGreaterThan(int age, Pageable pageable);
}
在服务层调用该方法时,就可以传入 PageRequest 对象来指定分页和排序规则:
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.example.repository.UserRepository;
import com.example.entity.User;

@Service
public class UserService {
@Autowired
private UserRepository userRepository;

public Page<User> getUsersByAgeGreaterThan(int age, int page, int size) {
    Sort sort = Sort.by(Sort.Direction.ASC, "username");
    Pageable pageable = PageRequest.of(page, size, sort);
    return userRepository.findByAgeGreaterThan(age, pageable);
}

}

posted @ 2025-02-20 19:30  Lomook  阅读(2)  评论(0)    收藏  举报