博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Grails In Action-05.Retrieving the data you need
阅读量:7118 次
发布时间:2019-06-28

本文共 3214 字,大约阅读时间需要 10 分钟。

hot3.png

第五章的内容是在Grails中查询功能的讲解。代码中讲解了模糊查询和标准查询两个例子,知识点如下:

  • where方法,这个方法是grails2.0版本后才新加进来的,作用是比较表达中的内容,并返回结果为真的对象
  • loginId =~ "%${query}%",=~的意思是创建一个普通的Java Matcher实例,对左右的内容进行比较、赋值
  • Profile.metaClass.properties*.name,查找元类型的属性名称
  • Profile.withCriteria,grails的标准查询
  • profileProps.grep(field) && value,元类型名称和参数名对比
  • ilike(field, value),hibernate hql的内容

先看看模糊查询。

模糊查询

新建一个查询页面,根据用户名查询用户信息。views/user/search.gsp,如果要正常访问到这个页面需要在UserController中增加一个访问闭包。

search页面

Search Hubbub
Search for Friends

search闭包

......def search = {}......

form中action="results",在controller中新建一个results闭包,处理提交信息并返回给results.gsp页面。

UserController

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负责将返回的信息显示到页面

results

Search Results

Results

Searched ${totalUsers} records for items matching ${term}. Found ${users.size()} hits.

  • ${user.loginId}
Search Again

标准查询

advSearch.gsp,查询页面

Advanced Search
Advanced Search for Friends
Name
Email
Homepage
Query Type:
${it.radio} ${it.label}

UserController.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,查询数据结果显示页面

Advanced Search Results

Advanced Results

Searched for items matching ${term}. Found ${profiles.size()} hits.

  • ${profile.fullName}
Search Again

转载于:https://my.oschina.net/65304586/blog/174786

你可能感兴趣的文章