Hibernate paging fuzzy query and hibernate fuzzy query

Source: Internet
Author: User

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}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.