第五章的內容是在Grails中查詢功能的講解。代碼中講解了模糊查詢和標準查詢兩個例子,知識點以下:html
先看看模糊查詢。閉包
新建一個查詢頁面,根據用戶名查詢用戶信息。views/user/search.gsp,若是要正常訪問到這個頁面須要在UserController中增長一個訪問閉包。hibernate
search頁面code
<!-- lang: groovy --> <html> <head> <title>Search Hubbub</title> <meta name="layout" content="main"/> </head> <body> <formset> <legend>Search for Friends</legend> <g:form action="results"> <label for="query">User Id</label> <g:textField name="query" /> <g:submitButton name="search" value="Search"/> </g:form> </formset> </body> </html>
search閉包orm
<!-- lang: groovy --> ...... def search = {} ......
form中action="results",在controller中新建一個results閉包,處理提交信息並返回給results.gsp頁面。htm
UserController對象
<!-- lang: groovy --> def results(String query) { def users = User.where { loginId =~ "%${query}%" }.list() return [ users: users,term: params.loginId,totalUsers: User.count() ] }
這個閉包接收query參數,返回查詢到的user對象列表,參數名和統計查詢到的user總數,results.gsp負責將返回的信息顯示到頁面it
resultsio
<!-- lang: groovy --> <html> <head> <title>Search Results</title> <meta name="layout" content="main"/> </head> <body> <h1>Results</h1> <p> Searched ${totalUsers} records for items matching <em>${term}</em>. Found <strong>${users.size()}</strong> hits. </p> <ul> <g:each var="user" in="${users}"> <li><g:link controller="user" action="show" id="${user.id}">${user.loginId}</g:link></li> </g:each> </ul> <g:link action='search'>Search Again</g:link> </body> </html>
advSearch.gsp,查詢頁面table
<!-- lang: groovy --> <html> <head> <title>Advanced Search</title> <meta name="layout" content="main"/> </head> <body> <formset> <legend>Advanced Search for Friends</legend> <table> <g:form action="advResults"> <tr> <td>Name</td> <td><g:textField name="fullName" /></td> </tr> <tr> <td>Email</td> <td><g:textField name="email" /></td> </tr> <tr> <td>Homepage</td> <td><g:textField name="homepage" /></td> </tr> <tr> <td>Query Type:</td> <td> <g:radioGroup name="queryType" labels="['And','Or','Not']" values="['and','or','not']" value="and" > ${it.radio} ${it.label} </g:radioGroup> </td> </tr> <tr> <td/> <td><g:submitButton name="search" value="Search"/></td> </tr> </g:form> </table> </formset> </body> </html>
UserController.groovy,控制器
<!-- lang: groovy --> def advSearch() { } def advResults() { def profileProps = Profile.metaClass.properties*.name def profiles = Profile.withCriteria { "${params.queryType}" { params.each { field, value -> if (profileProps.grep(field) && value) { ilike(field, value) } } } } [ profiles : profiles ] }
advResults.gsp,查詢數據結果顯示頁面
<!-- lang: groovy --> <html> <head> <title>Advanced Search Results</title> <meta name="layout" content="main"/> </head> <body> <h1>Advanced Results</h1> <p>Searched for items matching <em>${term}</em>. Found <strong>${profiles.size()}</strong> hits. </p> <ul> <g:each var="profile" in="${profiles}"> <li><g:link controller="profile" action="show" id="${profile.id}">${profile.fullName}</g:link></li> </g:each> </ul> <g:link action='advSearch'>Search Again</g:link> </body> </html>