当第一个实体是具有指定主键的实体之后的以下实体时,如何使用 JPA 获取列表
How to getList using JPA when the first entity is the following entity after the entity with specified primary key
要使用 limit
获取列表形式 offset
我可以使用:
@Override
public List<Collection> getList(int offset, int limit) {
String SELECT_COLLECTIONS = "select collection from " + Collection.class.getName() + " collection";
TypedQuery<Collection> query = entityManager.createQuery(SELECT_COLLECTIONS, Collection.class);
return query.setFirstResult(offset).setMaxResults(limit).getResultList();
}
现在我有一些实体的 主键 而不是偏移量。
如何获取@ID元素后面的元素后的List?
示例:我的数据库中的实体具有键 - a、b、c、d、e、f。
我需要执行getList(b, 3)。实体的结果列表将具有键 - c, d, e.
这行不通。对于当前数据,您可以 select
实体与 rank()
一起,找到指定 id 的 rank()
的值,然后使用它来查询以下数据(此功能是供应商特定的,例如可用在 postgres 中,sql 服务器)。但是您没有使用 order by
,导致结果排序未定义。在数据库中保存一些数据后,顺序可能会发生变化,结果也不会相同。
如果有可能你可以使用id
,那么你可以这样写:
"select collection from " + Collection.class.getName() + " collection where collection.id > :id order by collection.id";
并传递一个参数id
。
要使用 limit
获取列表形式 offset
我可以使用:
@Override
public List<Collection> getList(int offset, int limit) {
String SELECT_COLLECTIONS = "select collection from " + Collection.class.getName() + " collection";
TypedQuery<Collection> query = entityManager.createQuery(SELECT_COLLECTIONS, Collection.class);
return query.setFirstResult(offset).setMaxResults(limit).getResultList();
}
现在我有一些实体的 主键 而不是偏移量。
如何获取@ID元素后面的元素后的List?
示例:我的数据库中的实体具有键 - a、b、c、d、e、f。
我需要执行getList(b, 3)。实体的结果列表将具有键 - c, d, e.
这行不通。对于当前数据,您可以 select
实体与 rank()
一起,找到指定 id 的 rank()
的值,然后使用它来查询以下数据(此功能是供应商特定的,例如可用在 postgres 中,sql 服务器)。但是您没有使用 order by
,导致结果排序未定义。在数据库中保存一些数据后,顺序可能会发生变化,结果也不会相同。
如果有可能你可以使用id
,那么你可以这样写:
"select collection from " + Collection.class.getName() + " collection where collection.id > :id order by collection.id";
并传递一个参数id
。