上次说到了grails的几种关联关系,除此之外grails还提供了一些动态的方法给我们使用例如findAllBy,getAll,findWhere等,个人觉得还算好用吧,下面来分享下我的学习心得
一 简单的查询方法
1.findAllWhere的使用
在grails中find和findAll的区别是find默认取出查询出来的第一条的记录,findAll则是查询出全部记录
def useFindAllWhere() {
def city=CityInfo.findAllWhere(code:"HK",id:1)
Iterator<CityInfo> it=city.iterator();
def buf=new StringBuffer();
while(it.hasNext()){
CityInfo c=it.next();
buf.append(c.getId()+","+c.getName()+"\n");
}
render buf.toString();
}
2.getAll的使用
def useGetAll(){
def c=CityInfo.getAll([1,2,3])
Iterator<CityInfo> it=c.iterator();
def buf=new StringBuffer();
while(it.hasNext()){
CityInfo c1=it.next();
buf.append(c1.getId()+","+c1.getName()+"\n");
}
render buf.toString();
}
3.useFindAllBy的使用
这个方法特别厉害,by后面可以加下面的这些条件
LessThanLessThanEqualsGreaterThanGreaterThanEqualsBetweenLikeIlike (i.e. ignorecase like)IsNotNullIsNullNotEqualNotEqualAndOr def useFindAllBy(){
def c=CityInfo.findAllByIdBetween(5,35);
Iterator<CityInfo> it=c.iterator();
def buf=new StringBuffer();
while(it.hasNext()){
CityInfo c1=it.next();
buf.append(c1.getId()+","+c1.getName()+"\n");
}
render buf.toString();
}
4.使用find或findAll的时候同时使用hql
def useFindAll(){
def hql="from CityInfo where id>:id and code in:code";
def c=CityInfo.findAll(hql,["id":2,code:["NB","NJ"]])
Iterator<CityInfo> it=c.iterator();
def buf=new StringBuffer();
while(it.hasNext()){
CityInfo c1=it.next();
buf.append(c1.getId()+","+c1.getName()+"\n");
}
render buf.toString();
}
二 过滤器的使用
以前的web开发过滤器一般用来限制某些文件或文件夹的访问权限,grails的过滤器一般用来限制某些控制器或控制器的方法不能被直接访问。grails可以对某个或者全部控制器进行访问控制
针对这块的知识可以看看文档,文档上面貌似说的也不是很仔细。下面我写了个过滤器来限制所有控制器的访问,只要session为空并且访问的不是指定的方法就跳转到登录界面,有一点要注意就是过滤器以Filters结尾,一般来讲过滤器应放在grails-app/conf下面
package filter
class LoginFilters {
def filters = {
all(controller: ‘*‘,action:"*") {
before = {
if(session.user||actionName=="loginCheck"||actionName=="login") {
return true
}else{
redirect(uri:"/login/login")
return false;
}
}
after = { Map model ->
}
afterView = { Exception e ->
}
}
}
}
class LoginController {
def loginCheck(){
session.user="cry"
render "已经模拟登录"
}
def login(){
}
}
接下来访问登录的方法
接下来访问之前的控制器就不会跳转到登录界面了
grails过滤器和数据查询的几个重要方法,布布扣,bubuko.com
原文地址:http://blog.csdn.net/walkcode/article/details/25503843