Has anyone used the Criteria API to cycle through a list of properties form a hibernate-mapped bean and match a keyword on each of them? I got the code below to work, but I cannot figure out a way to apply the same concept on peoperties that are not of type String. It keeps throwing a ClassCastException. Anyone have any ideas?
Code:
/**
* Gets a like expression for a given
* column name and a keyword
* @param column
* @param keyword
* @return ilike Criterion
*/
private Criterion getLikeExp(String column,
String keyword){
return Expression.ilike(
column,
keyword,
MatchMode.ANYWHERE);
}
/**
* Gets an or expression that contains
* two like expressions for two given
* column names and a keyword
* @param column
* @param column2
* @param keyword
* @return or ilike Criterion
*/
private Criterion getLikeExp(String column,
String column2, String keyword){
Criterion cColumn2 = getLikeExp(column2, keyword);
return getLikeExp(column, cColumn2, keyword);
}
/**
* Gets an or expression that contains
* two like expressions for a given
* column name, an like expression
* that contains a second column name,
* and a keyword
* @param column
* @param cColumn2
* @param keyword
* @return or Criterion
*/
private Criterion getLikeExp(String column,
Criterion cColumn2, String keyword){
return Expression.or(
getLikeExp(column, keyword),
cColumn2
);
}
/**
* Searches a keyword based on a list of column names
* for a given Hibernate criteria class and returns the count
*/
public int keywordSearchCount(
Class criteriaClass,
String keyword,
List<String> columnNames) throws ClassCastException {
log.debug("keywordSearchCount()");
try {
int itemCount = 0;
Criteria criteria = HibernateUtil.getSession()
.createCriteria(
criteriaClass);
if(columnNames == null && !columnNames.isEmpty()){
Criterion c;
if(columnNames.size() == 1){
c = getLikeExp(columnNames.get(0), keyword);
} else {
c = getLikeExp(columnNames.get(1),
columnNames.get(0), keyword);
for(int i=(columnNames.size()-1); i>1; i--){
Criterion nxt =
getLikeExp(columnNames.get(i), c, keyword);
c = nxt;
}
}
criteria.add(c);
criteria.setProjection(Projections.rowCount());
itemCount = ((Integer)criteria
.uniqueResult()).intValue();
criteria.setProjection(null);
criteria.setResultTransformer(Criteria.ROOT_ENTITY);
}
return itemCount;
} catch (RuntimeException re) {
log.error("keywordSearchCount() failed", re);
throw re;
}
}
[/code]