I have the following object:
Agency
Name
Description
I would like to return hibernate object if the text "big" appers in any of the fields.
Is there a better way than SQL query:
select distinct id from agency where name l开发者_JAVA技巧ike 'big' or description like 'big'
in Hibernate?
EDITED:
I prefer to write a solution that is generic per class - that hibernate can check in any of the fields without specifying them
Criteria criteria = sess.createCriteria(Agency.class)
for (Field f : Agency.class.getDeclaredFields())
{
if(f.isAccessible()) {
criteria.add(Restrictions.like(f.getName(), "%big%"));
}
}
List agencies = criteria.list();
If you are annotating the classes then you can read the name.
To do so, the names of the field must match the columns. But you can capitalize them.
Critieria query
List agencies = sess.createCriteria(Agency.class)
.add( Restrictions.like("Name", "%big%") )
.add( Restrictions.like("Description", "%big%") )
.list();
Or you might need Or, depending on what you want:
List agencies = sess.createCriteria(Agency.class)
.add( Restrictions.or(
Restrictions..like("Name", "%big%"),
Restrictions.like("Description", "%big%")
) )
.list();
精彩评论