Hibernate Criteria API - 使用一个数据库查询更新许多行

时间:2016-05-24 05:07:05

标签: java hibernate hql hibernate-criteria criteria-api

我从这样的数据库中取出这样的人:

public List<Object[]> getLimitedBunchOfPersons(Integer limit) {

    Criteria criteria = getSession().createCriteria(Person.class, "person")
            .setProjection(
                    Projections.projectionList()
                      .add(Projections.property("person.personId"), "personId")
                      )
            .createAlias("person.status","status")
            .add(Restrictions.eq("status.statusId", 1L))
            .addOrder(Order.asc("person.createdOn"));

    return criteria.setMaxResults(limit).list();
}

因为我需要加快速度,所以我只获取了我实体的ID。需要注意的重要一点是,我操作大量行,而一个查询必须使用maxResults限制。

现在我的问题是,如何在一个数据库中使用Hibernate Criteria API轻松更新所有从前面提到的查询获取的行?

纯SQL查询将是这样的:

UPDATE PERSON
SET STATUS = 2, CREATED_ON = CURRENT_TIMESTAMP
WHERE STATUS = 1;

值得注意的是,更新方法必须使用相同的orderlimit作为getLimitedBunchOfPersons()方法。

1 个答案:

答案 0 :(得分:1)

对于单个对象,它将在您的代码

之后如下工作
/** * Loads an existing saved search. The saved search could have been created using the UI, or created using nlapiCreateSearch(type, filters, columns) in conjunction with nlobjSearch.saveSearch(title, scriptId). 
*<br>API Governance: 5 
* @param {String} recType [optional] - The record internal ID of the record type you are searching (for example, customer|lead|prospect|partner|vendor|contact). This parameter is case-insensitive. 
* @param {String} searchId - The internal ID or script ID of the saved search. The script ID of the saved search is required, regardless of whether you specify the search type. If you do not specify the search type, you must set type to null and then set the script/search ID. 
* @returns {nlobjSearch} nlobjSearch
* @since 2012.1 */ 
function nlapiLoadSearch(recType, searchId) { };

现在,如果列在列表中,您可以通过在List迭代中传递提到的代码来迭代列表