The Grails Tips series will introduce some of the experiences that I've summed up in grails development. This will avoid duplicating the official document, hoping to give the reader more valuable content with short articles.
Grom is an O/R mapping solution provided by the Grails framework. Through Grom can get rid of cumbersome SQL writing, and based on the results of search to automatically generate groovy implementation, you can save data Access layer code development, reduce the workload of programmers. Both JDO and S2JDBC in Java are such frameworks, and Grom's bottom is hibernate 3, a data-tier framework that is widely used in Java development.
(for the specific use of Grom, please refer to Grails's official grails user manual, which is not described here too much.) )
Grom provides many interfaces for executing SQL statements, including the result of using Slect statements to get count, such as using the following code to obtain the number of people surnamed Simpson.
def criteria = new Detachedcriteria. Build {eq ' lastName ', ' Simpson '}
def results = criteria.list (max:4, Sort: "FirstName")
The above example shows that the way to extract the number of search results, mainly for a certain table search, and in the actual commercial development, there are many data search is relatively complex. Multiple tables need to be combined, or they need to be combined with a child search to get search results.
For the former, it can be achieved through the loading function by setting the relationship between the goals. However, the latter need to use subqueries is gorm difficult to achieve. This is because the Gorm kernel itself is based on the hibernate, not only inherited the powerful advantages of O/R, but also inherited the inability to use subqueries of the soft rib.
In this case, my personal approach is to use groovy to access the database functionality, directly execute the SELECT statement, extract the execution results, as follows: 1. First define DEF DataSource in the corresponding service class, Grails will automatically insert your datasouce when it is executed.
2. Within the corresponding method in the service class, similar to the following execution and return results
def sql = new SQL (DataSource)
def result = Sql.firstrow (' Select COUNT (*) as "C" (select Max (c.id) from loveapple_contents C, Loveapple_site s\
where s.id = parent_site_id and s.id =? and Parent_category_alias =? GROUP by C.alias) T ',
[Site.id, Categoryalias]) return result
This code is a section of the tomato CMS in the extraction of the number of articles in the classification process.
(Of course, the usual site in the search for the number of articles is not so complicated, because the tomato CMS more functions, the data structure is more special, so you can only use subqueries.) Above is the author in grails development used in search count method, I hope to give you help.
Original address: Http://www.loveapple.cn/app/Grails/grails-chips-gorm-sql-count