Java Code Examples for javax.persistence.Query#setFirstResult()

The following examples show how to use javax.persistence.Query#setFirstResult() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProductSearch.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Searches for products
 * 
 * @return found VO services
 */
@SuppressWarnings("unchecked")
private List<Product> executeObjectQuery() {
    Query query = dm.createNativeQuery(sql, Product.class);
    setParameters(query);

    if (listCriteria.getOffset() > 0) {
        query.setFirstResult(listCriteria.getOffset());
        doCountQuery = true;
    }

    if (listCriteria.getLimit() >= 0) {
        query.setMaxResults(listCriteria.getLimit());
        doCountQuery = true;
    }

    List<Product> result = query.getResultList();
    return result;
}
 
Example 2
Source File: CommentServiceBean.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 分页查询评论内容
 * @param firstIndex
 * @param maxResult
 * @param userName 用户名称
 * @param isStaff 是否为员工
 * @return
 */
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public List<String> findCommentContentByPage(int firstIndex, int maxResult,String userName,boolean isStaff){
	List<String> topicContentList = new ArrayList<String>();//key:话题Id  value:话题内容
	
	String sql = "select o.content from Comment o where o.userName=?1 and o.isStaff=?2";
	Query query = em.createQuery(sql);	
	query.setParameter(1, userName);
	query.setParameter(2, isStaff);
	//索引开始,即从哪条记录开始
	query.setFirstResult(firstIndex);
	//获取多少条数据
	query.setMaxResults(maxResult);
	
	List<Object> objectList = query.getResultList();
	if(objectList != null && objectList.size() >0){
		for(int i = 0; i<objectList.size(); i++){
			String content = (String)objectList.get(i);
			topicContentList.add(content);
		}
	}
	
	return topicContentList;
}
 
Example 3
Source File: DatabaseNetwork.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return all vertices matching the filter.
 */
@SuppressWarnings("unchecked")
public synchronized List<Vertex> findAllLike(String filter, int pageSize, int page) {
	Query query = null;
	if (filter.indexOf('*') == -1) {
		query = this.entityManager.createQuery("Select v from Vertex v where v.dataValue = :filter");
		query.setParameter("filter", filter);
	} else {
		query = this.entityManager.createQuery("Select v from Vertex v where v.dataValue like :filter");
		query.setParameter("filter", filter.replace('*', '%'));			
	}
	setHints(query);
	query.setFirstResult(page * pageSize);
	query.setMaxResults(pageSize);
	return query.getResultList();
}
 
Example 4
Source File: CommonDAOSpringImpl.java    From EasyEE with MIT License 6 votes vote down vote up
@Override
public List findTop(String jpql, int topCount, Map<String, Object> values) {

	Query query = entityManager.createQuery(jpql);
	query.setFirstResult(0);
	query.setMaxResults(topCount);

	if (values != null && values.size() > 0) {
		for (Entry<String, Object> e : values.entrySet()) {
			query.setParameter(e.getKey(), e.getValue());
		}
	}

	List list = query.getResultList();
	return list;
}
 
Example 5
Source File: DummyGameEndpoint.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Called when the player unlocked an achievement.
 *
 * @param achievement the achievement unlocked by the player.
 * @throws ServiceException
 */
public void achievementUnlocked(@Named("message") String achievement, User user)
    throws ServiceException {

  if (user == null && !Configuration.ALLOW_UNAUTHENTICATED_CALLS) {
    throw new UnauthorizedException("Only authenticated calls are allowed");
  }

  // The actual game backend would probably validate the achievement first
  // and then store it in Datastore. Then it might send push notification
  // to user's friends.
  // In this sample only the send part is implemented and instead of
  // retrieving the list of user's friends, the code just retrieves
  // a few most recently registered devices and sends an alert to them

  String playerName =
      (user == null || user.getEmail() == null) ? "Anonymous User" : user.getEmail();

  String alert = String.format("%1$s unlocked achievement '%2$s'", playerName, achievement);

  EntityManager mgr = null;
  try {
    mgr = getEntityManager();
    Query query =
        mgr.createQuery("select deviceToken from DeviceRegistration d order by timestamp");

    query.setFirstResult(0);
    query.setMaxResults(5);

    @SuppressWarnings("unchecked")
    List<String> deviceTokensOfFriends = query.getResultList();

    log.info("Sent achievement unlocked push notification to " + deviceTokensOfFriends.size()
        + " friend(s) of " + playerName);
    PushNotificationUtility.enqueuePushAlert(alert, deviceTokensOfFriends);
  } finally {
    mgr.close();
  }
}
 
Example 6
Source File: ManagerBean.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public List get(EntityManager entityManager, Class clazz, String sidx, String sord, int start, int limit, List<Criteria> masks, boolean strictMasks) {
   String sql = "SELECT o FROM " + clazz.getSimpleName() + " o ";
   sql = sql + this.addMasks(masks, strictMasks);
   if (sidx != null && !"".equals(sidx)) {
      sql = sql + " ORDER BY o." + sidx + " " + sord;
   }

   Query q = entityManager.createQuery(sql);
   this.setParameterMasks(masks, q);
   q.setFirstResult(start);
   q.setMaxResults(limit);
   LOG.debug("SQL get:" + sql);
   return q.getResultList();
}
 
Example 7
Source File: CustomBaseSqlDaoImpl.java    From tianti with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Map<String, Object>> querySqlObjects(String sql, Object params, Integer currentPage,Integer rowsInPage){
	Query qry = em.createNativeQuery(sql);
	SQLQuery s = qry.unwrap(SQLQuery.class);
	
	//设置参数
	if(params != null){
		if(params instanceof List){
			List<Object> paramList = (List<Object>) params;
			for(int i = 0, size = paramList.size(); i < size; i++){
				qry.setParameter(i+1, paramList.get(i));
			}
		}else if(params instanceof Map){
			Map<String, Object> paramMap = (Map<String, Object>) params;
			for(String key : paramMap.keySet()){
				qry.setParameter(key, paramMap.get(key));
			}
		}
	}
	
	if (currentPage != null && rowsInPage != null) {//判断是否有分页
		// 起始对象位置
		qry.setFirstResult(rowsInPage * (currentPage - 1));
		// 查询对象个数
		qry.setMaxResults(rowsInPage);
	}
	s.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
	List<Map<String, Object>> resultList=new ArrayList<Map<String, Object>>();
	try {
		resultList=s.list();
	} catch (Exception e) {
	}finally{
		em.close();
	}
	return resultList;
}
 
Example 8
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore.
 * It uses HTTP GET method and paging support.
 *
 * @return A CollectionResponse class containing the list of all entities
 * persisted and a cursor to the next page.
 */
@SuppressWarnings({"unchecked", "unused"})
@ApiMethod(name = "listCheckIn")
public CollectionResponse<CheckIn> listCheckIn(
    @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;
  Cursor cursor = null;
  List<CheckIn> execute = null;

  try {
    mgr = getEntityManager();
    Query query = mgr.createQuery("select from CheckIn as CheckIn");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<CheckIn>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null) cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (CheckIn obj : execute);
  } finally {
    mgr.close();
  }

  return CollectionResponse.<CheckIn>builder()
      .setItems(execute).setNextPageToken(cursorString).build();
}
 
Example 9
Source File: CommonDAOSpringImpl.java    From EasyEE with MIT License 5 votes vote down vote up
@Override
public void findByPage(PageBean pageBean, Map<String, Object> values) {
	String jpql = pageBean.getQuery() != null ? pageBean.getQuery() : pageBean.getAutoQuery();

	Query query = createQuery(entityManager, jpql, false, null, values);
	query.setFirstResult(pageBean.getRowStart());
	query.setMaxResults(pageBean.getRowsPerPage());

	pageBean.setData(query.getResultList());

	String queryString = "";
	int end = jpql.length();
	if (jpql.indexOf("order by") != -1) {
		end = jpql.indexOf("order by");
	}
	if (jpql.toUpperCase().indexOf("SELECT") != -1) {
		int i = jpql.toUpperCase().indexOf("FROM");
		queryString = "select count(1) " + jpql.substring(i, end);
	} else {
		queryString = "select count(1) " + jpql.substring(0, end);
	}

	// 去掉ORDER BY 的部分
	int j = queryString.toUpperCase().lastIndexOf("ORDER");
	if (j != -1) {
		queryString = queryString.substring(0, j);
	}
	Query cquery = createQuery(entityManager, queryString, false, null, values);

	int maxRow = (Integer.valueOf(cquery.getSingleResult().toString())).intValue();
	pageBean.setRowsCount(maxRow);

}
 
Example 10
Source File: AbstractQueryExecutorImpl.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
protected Query setupQuery(Query typedQuery) {
	// apply graph control
	applyFetchPaths(typedQuery);

	// control Hibernate query caching
	if (cached) {
		typedQuery.setHint("org.hibernate.cacheable", Boolean.TRUE);
	}

	if (limit > 0) {
		typedQuery.setMaxResults(limit);
	}
	typedQuery.setFirstResult(offset);
	return typedQuery;
}
 
Example 11
Source File: AbstractAnyDAO.java    From syncope with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected List<String> findAllKeys(final String table, final int page, final int itemsPerPage) {
    Query query = entityManager().createNativeQuery(
            "SELECT id FROM " + table + " ORDER BY id", String.class);
    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));
    query.setMaxResults(itemsPerPage);

    List<String> result = new ArrayList<>();
    query.getResultList().stream().map(resultKey -> resultKey instanceof Object[]
            ? (String) ((Object[]) resultKey)[0]
            : ((String) resultKey)).
            forEach(actualKey -> result.add(actualKey.toString()));
    return result;
}
 
Example 12
Source File: PageInfo.java    From springBoot with MIT License 5 votes vote down vote up
/**
 * 获取JPA的分页对象
 */
public static Page readPage(Query query, Pageable pageable, Query countQuery) {
    if (pageable.isPaged()) {
        query.setFirstResult((int) pageable.getOffset());
        query.setMaxResults(pageable.getPageSize());
    }
    return PageableExecutionUtils.getPage(query.getResultList(), pageable, () -> executeCountQuery(countQuery));
}
 
Example 13
Source File: CdiQueryInvocationContext.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public Query applyRestrictions(Query query)
{
    Parameters params = getParams();
    Method method = getMethod();
    
    if (params.hasSizeRestriction())
    {
        query.setMaxResults(params.getSizeRestriciton());
    }
    
    if (params.hasFirstResult())
    {
        query.setFirstResult(params.getFirstResult());
    }
    
    LockModeType lockMode = extractLockMode();
    if (lockMode != null)
    {
        query.setLockMode(lockMode);
    }
    
    QueryHint[] hints = extractQueryHints();
    if (hints != null)
    {
        for (QueryHint hint : hints)
        {
            query.setHint(hint.name(), hint.value());
        }
    }

    applyEntityGraph(query, method);
    query = applyJpaQueryPostProcessors(query);
    return query;
}
 
Example 14
Source File: UserGroupDao.java    From development with Apache License 2.0 5 votes vote down vote up
public List<Product> getAccessibleServices(String unitId,
        Pagination pagination, String marketplaceId) {
    Query query = dm.createNamedQuery("UserGroup.findAccessibleServices");
    query.setParameter("userGroupKey", Long.valueOf(unitId));
    query.setParameter("marketplaceKey", Long.valueOf(marketplaceId));
    query.setFirstResult(pagination.getOffset());
    query.setMaxResults(pagination.getLimit());
    List<Product> accessibleProducts = ParameterizedTypes.list(
            query.getResultList(), Product.class);
    return accessibleProducts;
}
 
Example 15
Source File: JpaStorage.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * @see io.apiman.manager.api.core.IStorageQuery#getContracts(java.lang.String, java.lang.String, java.lang.String, int, int)
 */
@Override
public List<ContractSummaryBean> getContracts(String organizationId, String apiId,
        String version, int page, int pageSize) throws StorageException {
    int start = (page - 1) * pageSize;
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
                String jpql =
                "SELECT c from ContractBean c " +
                "  JOIN c.api apiv " +
                "  JOIN apiv.api api " +
                "  JOIN c.client clientv " +
                "  JOIN clientv.client client " +
                "  JOIN api.organization sorg" +
                "  JOIN client.organization aorg" +
                " WHERE api.id = :apiId " +
                "   AND sorg.id = :orgId " +
                "   AND apiv.version = :version " +
                " ORDER BY sorg.id, api.id ASC";
        Query query = entityManager.createQuery(jpql);
        query.setParameter("orgId", organizationId);
        query.setParameter("apiId", apiId);
        query.setParameter("version", version);
        query.setFirstResult(start);
        query.setMaxResults(pageSize);
        List<ContractBean> contracts = query.getResultList();
        List<ContractSummaryBean> rval = new ArrayList<>(contracts.size());
        for (ContractBean contractBean : contracts) {
            ClientBean client = contractBean.getClient().getClient();
            ApiBean api = contractBean.getApi().getApi();
            PlanBean plan = contractBean.getPlan().getPlan();

            OrganizationBean clientOrg = entityManager.find(OrganizationBean.class, client.getOrganization().getId());
            OrganizationBean apiOrg = entityManager.find(OrganizationBean.class, api.getOrganization().getId());

            ContractSummaryBean csb = new ContractSummaryBean();
            csb.setClientId(client.getId());
            csb.setClientOrganizationId(client.getOrganization().getId());
            csb.setClientOrganizationName(clientOrg.getName());
            csb.setClientName(client.getName());
            csb.setClientVersion(contractBean.getClient().getVersion());
            csb.setContractId(contractBean.getId());
            csb.setCreatedOn(contractBean.getCreatedOn());
            csb.setPlanId(plan.getId());
            csb.setPlanName(plan.getName());
            csb.setPlanVersion(contractBean.getPlan().getVersion());
            csb.setApiDescription(api.getDescription());
            csb.setApiId(api.getId());
            csb.setApiName(api.getName());
            csb.setApiOrganizationId(apiOrg.getId());
            csb.setApiOrganizationName(apiOrg.getName());
            csb.setApiVersion(contractBean.getApi().getVersion());

            rval.add(csb);
        }
        return rval;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}
 
Example 16
Source File: FirstResultPostProcessor.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@Override
public Query postProcess(CdiQueryInvocationContext context, Query query)
{
    query.setFirstResult(startPosition);
    return query;
}
 
Example 17
Source File: JPAResourceStore.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public List<Resource> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ResourceEntity> querybuilder = builder.createQuery(ResourceEntity.class);
    Root<ResourceEntity> root = querybuilder.from(ResourceEntity.class);
    querybuilder.select(root.get("id"));
    List<Predicate> predicates = new ArrayList();

    if (resourceServerId != null) {
        predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServerId));
    }

    attributes.forEach((name, value) -> {
        if ("id".equals(name)) {
            predicates.add(root.get(name).in(value));
        } else if ("scope".equals(name)) {
            predicates.add(root.join("scopes").get("id").in(value));
        } else if ("ownerManagedAccess".equals(name) && value.length > 0) {
            predicates.add(builder.equal(root.get(name), Boolean.valueOf(value[0])));
        } else if ("uri".equals(name) && value.length > 0 && value[0] != null) {
            predicates.add(builder.lower(root.join("uris")).in(value[0].toLowerCase()));
        } else if ("uri_not_null".equals(name)) {
            // predicates.add(builder.isNotEmpty(root.get("uris"))); looks like there is a bug in hibernate and this line doesn't work: https://hibernate.atlassian.net/browse/HHH-6686
            // Workaround
            Expression<Integer> urisSize = builder.size(root.get("uris"));
            predicates.add(builder.notEqual(urisSize, 0));
        } else if ("owner".equals(name)) {
            predicates.add(root.get(name).in(value));
        } else if (!Resource.EXACT_NAME.equals(name)) {
            if ("name".equals(name) && attributes.containsKey(Resource.EXACT_NAME) && Boolean.valueOf(attributes.get(Resource.EXACT_NAME)[0]) 
                    && value.length > 0 && value[0] != null) {
                predicates.add(builder.equal(builder.lower(root.get(name)), value[0].toLowerCase()));
            } else if (value.length > 0 &&  value[0] != null) {
                predicates.add(builder.like(builder.lower(root.get(name)), "%" + value[0].toLowerCase() + "%"));
            }
        }
    });

    querybuilder.where(predicates.toArray(new Predicate[predicates.size()])).orderBy(builder.asc(root.get("name")));

    Query query = entityManager.createQuery(querybuilder);

    if (firstResult != -1) {
        query.setFirstResult(firstResult);
    }
    if (maxResult != -1) {
        query.setMaxResults(maxResult);
    }

    List<String> result = query.getResultList();
    List<Resource> list = new LinkedList<>();
    ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();

    for (String id : result) {
        Resource resource = resourceStore.findById(id, resourceServerId);

        if (resource != null) {
            list.add(resource);
        }
    }

    return list;
}
 
Example 18
Source File: JPAPolicyStore.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public List<Policy> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<PolicyEntity> querybuilder = builder.createQuery(PolicyEntity.class);
    Root<PolicyEntity> root = querybuilder.from(PolicyEntity.class);
    List<Predicate> predicates = new ArrayList();
    querybuilder.select(root.get("id"));

    if (resourceServerId != null) {
        predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServerId));
    }

    attributes.forEach((name, value) -> {
        if ("permission".equals(name)) {
            if (Boolean.valueOf(value[0])) {
                predicates.add(root.get("type").in("resource", "scope", "uma"));
            } else {
                predicates.add(builder.not(root.get("type").in("resource", "scope", "uma")));
            }
        } else if ("id".equals(name)) {
            predicates.add(root.get(name).in(value));
        } else if ("owner".equals(name)) {
            predicates.add(root.get(name).in(value));
        } else if ("owner_is_not_null".equals(name)) {
            predicates.add(builder.isNotNull(root.get("owner")));
        } else if ("resource".equals(name)) {
            predicates.add(root.join("resources").get("id").in(value));
        } else if ("scope".equals(name)) {
            predicates.add(root.join("scopes").get("id").in(value));
        } else if (name.startsWith("config:")) {
            predicates.add(root.joinMap("config").key().in(name.substring("config:".length())));
            predicates.add(builder.like(root.joinMap("config").value().as(String.class), "%" + value[0] + "%"));
        } else {
            predicates.add(builder.like(builder.lower(root.get(name)), "%" + value[0].toLowerCase() + "%"));
        }
    });

    if (!attributes.containsKey("owner") && !attributes.containsKey("owner_is_not_null")) {
        predicates.add(builder.isNull(root.get("owner")));
    }

    querybuilder.where(predicates.toArray(new Predicate[predicates.size()])).orderBy(builder.asc(root.get("name")));

    Query query = entityManager.createQuery(querybuilder);

    if (firstResult != -1) {
        query.setFirstResult(firstResult);
    }
    if (maxResult != -1) {
        query.setMaxResults(maxResult);
    }

    List<String> result = query.getResultList();
    List<Policy> list = new LinkedList<>();
    for (String id : result) {
        Policy policy = provider.getStoreFactory().getPolicyStore().findById(id, resourceServerId);
        if (Objects.nonNull(policy)) {
            list.add(policy);
        }
    }
    return list;
}
 
Example 19
Source File: QuestionServiceBean.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 分页查询问题
 * @param firstIndex 开始索引
 * @param maxResult 需要获取的记录数
 * @return
 */
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public List<Question> findQuestionByPage(int firstIndex, int maxResult){
	List<Question> questionList = new ArrayList<Question>();
	
	String sql = "select o.id,o.title,o.content,o.appendContent," +
			"o.postTime,o.userName,o.isStaff,o.status " +
			" from Question o ";

	Query query = em.createQuery(sql);	
	
	//索引开始,即从哪条记录开始
	query.setFirstResult(firstIndex);
	//获取多少条数据
	query.setMaxResults(maxResult);
		
	List<Object[]> objectList = query.getResultList();
	if(objectList != null && objectList.size() >0){
		for(int i = 0; i<objectList.size(); i++){
			Object[] obj = (Object[])objectList.get(i);
			Long id = (Long)obj[0];
			String title = (String)obj[1];
			String content = (String)obj[2];
			String appendContent = (String)obj[3];
			Date postTime = (Date)obj[4];
			String userName = (String)obj[5];
			Boolean isStaff = (Boolean)obj[6];
			Integer status = (Integer)obj[7];

			Question question = new Question();
			question.setId(id);
			question.setTitle(title);
			question.setContent(content);
			question.setAppendContent(appendContent);
			question.setPostTime(postTime);
			question.setUserName(userName);
			question.setIsStaff(isStaff);
			question.setStatus(status);
			questionList.add(question);
			
		}
	}
	return questionList;
}
 
Example 20
Source File: JqlUtils.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
/**
     * 利用 JQL 语句进行分页查询
     * JQL 需在 Hibernate 环境中,entityManager 管理 Entity(表)
     * 分页需要进行两次查询
     * 排序条件不在这里维护,在 JQL 语句中。计算总数的语句和查询语句不同,计算总数的语句可以简化很多条件,所以分开写
     *
     * @param em            注入 JdbcTemplate 方法
     *                      //@Autowired EntityManager em;
     *                      -
     *                      如果是多数据源,在可以指定数据源
     * @param queryJql      查询 JQL 语句 ,和不分页时相同,含 Order 如
     *                      String query = "select s.* from Something s "
     *                      + "join somethingelse selse on selse.id = s.fk_somethingelse "
     *                      + "where selse.id = :somethingElseId "
     *                      + "order by selse.date";
     * @param queryArgs     arguments to bind to the query ,查询时,绑定在 queryJql 上的参数,按照位置对应
     *                      按照占位参数的位置,逐个对应 Object[] 中的参数, query.setParameter(i, queryArgs[i]);
     *                      -
     *                      (leaving it to the PreparedStatement to guess the corresponding SQL type ,是 Object 类型,系统可以自动匹配成 sql 类型)
     *                      无参数时,传入 new Objects[]{} 空数组即可
     *                      占位符方式,可以避免 sql 注入  Queries with Named Parameters
     * @param countJql      计算总数的 JQL 语句 , 如
     *                      String countQuery = "select count(s.*) from Something s "
     *                      + "join somethingelse selse on selse.id = s.fk_somethingelse "
     *                      + "where selse.id = :somethingElseId ";
     * @param countArgs     计算总数时,绑定 countJql 上的参数
     * @param currentPageNo 当前页码,从 1 开始
     * @param pageSize      页大小
     * @param resultClass   自定义返回值类型,一般为 Bean
     * @param <T>
     * @return
     */
    private static <T> PageBean<T> queryPageByJQLString(final EntityManager em,
                                                        final String queryJql, Object[] queryArgs,
                                                        final String countJql, Object[] countArgs,
                                                        int currentPageNo, int pageSize, Class<T> resultClass) {


        log.info("queryJqlString : \n {} ", queryJql);
        log.info("countJqlString : \n {} ", countJql);


        Assert.isTrue(currentPageNo >= 1, "currentPageNo : 起始页不应小于 1 ,且从 1 开始。");
        Assert.isTrue(pageSize >= 0, "pageSize : 页大小不能小于 0");
        Assert.isTrue(countJql.contains("count"), "queryNativeSql 和 countNativeSql 参数顺序不对");

        // 计算总数
        Query queryTotal = em.createQuery(countJql);
        for (int i = 0; i < countArgs.length; i++)
            queryTotal.setParameter(i, countArgs[i]);
        int totalRecordsSize = (int) queryTotal.getSingleResult();


        if (totalRecordsSize == 0)
            return new PageBean(pageSize, 0 + 1, 0, Collections.EMPTY_LIST); //currentPageNo 从 1 开始
//        log.info("totalRecordsSize : " + totalRecordsSize);
        //分页
        Query query = em.createQuery(queryJql);
        query.setFirstResult((currentPageNo - 1) * pageSize);
        query.setMaxResults(pageSize);
//        final List<Object[]> content = query.getResultList();
//        List<Something> somethingList = Lists.newArrayList();
//        content.forEach(object -> somethingList.add(//map obj to something));

        // 可以代替上述?未测试
        query.unwrap(resultClass); // 返回值包装

        //Bind an argument value to a positional parameter.
        for (int i = 0; i < queryArgs.length; i++)
            query.setParameter(i, queryArgs[i]);
        List<T> content = query.getResultList();

        return new PageBean(pageSize, currentPageNo, totalRecordsSize, content);
    }