微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

春季数据分页JPA(极限和偏移)

我希望用户能够在查询方法中指定限制(返回的大小)和偏移量(返回的第一条记录/索引).

这是我没有任何分页功能的类.
我的实体:

@Entity
public Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    @Column(name="NAME")
    private String name;

    //getters and setters
}

我的仓库:

public interface EmployeeRepository extends JpaRepository<Employee,Integer> {

    @Query("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id")
    public List<Employee> findByName(@Param("name") String name);
}

我的服务界面:

public interface EmployeeService {

    public List<Employee> findByName(String name);
}

我的服务实现:

public class EmployeeServiceImpl {

    @Resource
    EmployeeRepository repository;

    @Override
    public List<Employee> findByName(String name) {
        return repository.findByName(name);
    }
}

现在我试图提供支持偏移和限制的分页功能.
我的实体类保持不变.

我的“新”存储库具有可分页参数:

public interface EmployeeRepository extends JpaRepository<Employee,Integer> {

    @Query("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id")
    public List<Employee> findByName(@Param("name") String name,Pageable pageable);
}

我的“新”服务界面有两个附加参数:

public interface EmployeeService {

    public List<Employee> findByName(String name,int offset,int limit);
}

我的“新”服务实现:

public class EmployeeServiceImpl {

    @Resource
    EmployeeRepository repository;

    @Override
    public List<Employee> findByName(String name,int limit) {
        return repository.findByName(name,new PageRequest(offset,limit);
    }
}

这不是我想要的. PageRequest指定页面和大小(页面页面的大小).现在指定大小正是我想要的,但是,我不想指定起始页面#,我希望用户能够指定起始记录/索引.我想要类似的东西

public List<Employee> findByName(String name,int limit) {
    TypedQuery<Employee> query = entityManager.createquery("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id",Employee.class);
    query.setFirstResult(offset);
    query.setMaxResults(limit);
    return query.getResultList();
}

特别是setFirstResult()和setMaxResult()方法.但是我不能使用这个方法,因为我想使用Employee存储库接口. (或者实际上是通过entityManager定义查询更好)?无论如何,是否有一种方法来指定偏移而不使用entityManager?提前致谢!

解决方法

你可能不能用spring数据jpa来这个.如果偏移量非常小,您可能会在检索后从查询删除前X个语句.

否则,您可以将页面大小定义为偏移量,并从第1页开始.

原文地址:https://www.jb51.cc/java/122513.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐