2017-06-22 118 views
1

請幫我,Spring/Hibernate Select Count(*)Query Customizing?

這是我的DAO,給了我正確的行數,但我想添加一些條件。

@Override 
public int getAllRows(SearchForm searchForm) { 
    logger.info("SearchForm Detail :: " + searchForm); 
    Session session = this.sessionFactory.getCurrentSession(); 
    Query query = (Query) session.createQuery(" select count(*) from EmployeeVO"); 
    int rows = ((Number) query.uniqueResult()).intValue(); 
    logger.info("Number of Rows :: " + rows); 
    return rows; 
} 

這是我的MySQL查詢:

選擇 FIRST_NAME

FROM 員工

WHERE FIRST_NAME LIKE '%AB%'

和 工資> 0,工資< 100000;

回答

0
Query query = (Query) session.createQuery("SELECT first_name FROM employees WHERE first_name LIKE ? AND salary > ? and salary < ?"); 
query.setParameter(0, '%ab%'); 
query.setParameter(1, 0); 
query.setParameter(2, 100000); 

也可以使用命名參數也如下:

Query query = (Query) session.createQuery("SELECT first_name FROM employees WHERE first_name LIKE :first_name AND salary > :min_salary and salary < :max_salary"); 
query.setParameter(first_name, '%ab%'); 
query.setParameter(min_salary, 0); 
query.setParameter(max_salary, 100000); 

另一替換是使用Hibernate標準API:

Criteria criteria = session.createCriteria(Employee.class); 
criteria.add(Restrictions.eq("first_name", "%ab%")); 
criteria.add(Restrictions.lt("salary ", 0)); 
criteria.add(Restrictions.gt("salary ", 100000)); 
List list = criteria.list(); 
+0

此外,可以在更鬆散耦合調整它方式: USE: query.setParameter(first_name,「%」+ searchForm.getFirstName()+「%」); – GaurZilla

+0

謝謝你的回答,但是我想在where子句中定製「first_name」,我可以用嗎?而不是first_name和setString? – oldmidas

+0

@oldmidas否。你不能參數化first_name屬性來在運行時傳遞值。 –