Get the App
SLTechnology News&Howtos  ›  Servers  › 

The implementation method of reusing query conditions and paging in Grails

Shulou Source: shulou.com Published: 2022-06-01 16:45:18 10月02日 Update

This article introduces the relevant knowledge of "Grails reuse query conditions and paging". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

After reading several articles about grails paging, most of them complicate simple things, and there is no reuse of query conditions. When paging, where conditions are the same when seeking count and list. Better programmers will reuse where conditions. In grails, they must make use of closure features to reuse them. Just take a look at the following code.

Def serach = {if (! params.max) params.max = 10 if (! params.offset) params.offset = 0 if (! params.sort) params.sort = "id" if (! params.order) params.order = "asc" def cel = {if ( Params.name) {like ("name" "% ${params.name}%")} if (params.city) {like ("city", "% ${params.city}%")}} def results = User.createCriteria () .list (params Cel) / / def cut = User.createCriteria () .count (cel) [userInstanceList: results, userInstanceTotal: results.totalCount]}

See, the del closure reuses ~, and you need to note that when you list, you will return a PagedResultList type with a totalCount attribute in it, so you don't have to write the annotated code, otherwise three SQL will be sent. This is mainly demonstrated by using closures to reuse query conditions.

In addition, let's talk about the practice in hibernate and ibatis. Hibernate usually does this, encapsulating a method:

Private Criteria getCriteria (Dept dept) {Criteria criteria = super.getSession () .createCriteria (Dept.class); criteria.addOrder (Order.desc ("id")) / / reverse if (dept! = null) {if (dept.getId ()! = null & & dept.getId () > 0) {criteria.add ("id", dept.getId () } if (StringUtils.isNotBlank (dept.getName () {criteria.add (Restrictions.like ("name", setPropertyValue (dept.getName () } if (StringUtils.isNotBlank (dept.getDesp () {criteria.add (Restrictions.like ("desp", setPropertyValue (dept.getDesp ();}} return criteria;}

This way it can be reused.

This is the end of the content of "Grails reuse query conditions and paging". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Conditions reuse queries methods closures code content time more knowledge complexity practicality success in learning next no need things reverse order practice dilemma reality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MariaDB Microsoft Docker MySQL