1.addTo*
为领域类添加一对多或多对多的关系。
def fictBook = new Book(title:"IT")
def nonFictBook = new Book(title:"On Writing: A Memoir of the Craft")
def a = new Author(name:"Stephen King")
.addToFiction(fictBook) // 'fiction' is name of relationship property
.addToNonFiction(nonFictBook) // 'nonFiction' is name of relationship property
.save()
2.constraints
定义验证的约束。
class Book {
String title
Author author
static constraints = {
title(blank:false, nullable:false, size:5..150)
author(nullable:false)
}
}
3.count
统计数据库中领域类实例的个数。
def noOfBooks = Book.count()
4.countBy*
使用领域类的属性进行统计
class Book {
Long id
Long version
String title
Date releaseDate
String author
}
def c = Book.countByTitle("The Shining")
c = Book.countByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
c = Book.countByReleaseDateBetween(firstDate, new Date())
c = Book.countByReleaseDateGreaterThanEquals(firstDate)
c = Book.countByTitleLike("%Hobbit%")
c = Book.countByTitleNotEqual("Harry Potter")
c = Book.countByReleaseDateIsNull()
c = Book.countByReleaseDateIsNotNull()
5.createCriteria
创建一个Grails的HibernateCriteriaBuilder,用于创建条件查询。
def c = Account.createCriteria()
def results = c.list {
like("holderFirstName", "Fred%")
and {
between("balance", 500, 1000)
eq("branch", "London")
}
maxResults(10)
order("holderLastName", "desc")
}
6.delete
7.errors
Spring Errors接口的实例,可能包含数据绑定或验证的错误。
def user = new User(params)
if(user.validate()) {
// do something with user
}
else {
user.errors.allErrors.each {
println it
}
}
8.discard
通知一次变更不进行持久化,等同于使用Hibernate的evict方法。只是为了防止Grails的自动持久化。
def b = Book.get(1)
b.title = "Blah"
b.discard() // changes won't be applied now
9.executeQuery
10.executeUpdate
11.exists
12.find
如果没有找到返回null。
// Dan brown's first book
Book.find("from Book as b where b.author='Dan Brown'")
// with a positional parameter
Book.find("from Book as b where b.author=?",['Dan Brown'])
// with a named parameter (since 0.5)
Book.find("from Book as b where b.author=:author",[author:'Dan Brown'])
// query by example
def b = new Book(author:"Dan Brown")
Book.find(b)
13.findAll
14.findAllBy*
15.findWhere
16.get
根据id获取领域类实例,找不到返回null
17.getAll
根据id集获取领域类实例。
18.hasErrors
如果在合法性验证、保存或数据绑定时发生错误返回true。
19.ident
20.list
21.listOrderBy
22.lock
主键使用uuid生成:
static mapping = {
version false
//主键重新定义
id generator:'uuid.hex',name:"uuid",colunm:"uuid"
}
最后欢迎大家访问我的个人网站:1024s