Hibernate paging fuzzy query and hibernate fuzzy query
In web projects, display data is usually displayed by page. At the same time, users may still need to search, that is, fuzzy query, we need to write a paging and dynamic conditional query method in dao. Paging is relatively simple. It uses paging provided by hibernate, and uses map ("field", fuzzy value) to encapsulate query conditions for dynamic conditions. map can add multiple query conditions, which is a good choice, to achieve paging and fuzzy query.
1 @ Override 2 public List <T> findPage (int page, int length, Map <String, Object> pram) {3 List <T> result = null; 4 try 5 {
// Initialize hql, this. entityClazz. getSimpleName () is the real class name of the generic type. In the constructor, obtain 6 String hql = "from" + this. entityClazz. getSimpleName () + "where 1 = 1 and"; // note the space
7 Session session = this. sesionFactory. openSession (); // get the connection 8 if (! Pram. isEmpty () // determines whether there is an unconditional 9 {10 Iterator <String> it = pram. keySet (). iterator (); // iterations map11 while (it. hasNext () 12 {13 String key = it. next (); // obtain the key in the condition map, that is, the condition field 14 hql = hql + key + "like" + "'%" + pram. get (key) + "% '" + "and"; // concatenate fields and fuzzy values into hql15} 16} 17 18 hql + = "2 = 2 "; // Add 2 = 2 at the end of hql to facilitate hql to splice 19 System. out. println (hql); 20 Query query = session. createQuery (hql); 21 query. setFirstResult (page-1) * length); // set the page number 22 query. setMaxResults (length); // set the data length per page to 23 result = query. list (); // return result set 24 25} catch (RuntimeException re) 26 {27 throw re; 28} 29 30 return result; 31 32}