Grails学习笔记之GORM

1.关联查询
假设有以下领域对象:

class Account{
Transaction transaction
Date created
}

class Transaction{
Date date
}


def c = Account.createCriteria()
def now = new Date()
def results = c.list {
transaction {//查询关联的属性
between('date',now-10, now)
}
eq("transaction.id", 1 as Long)//如果是关联的id可以这样查询(many to one / one to one)
}



def c = Account.createCriteria()
def now = new Date()
def results = c.list {
eq("transaction.date", new Date())//运行时出错,关联除id外的属性不能这样查询
}


2.批量查询关联
batchSize: N,N是指查询关联的个数,而不是关联元素个数(当关联为集合时)。

class Person {
String firstName
Pet pet
static mapping = {
pet batchSize: 5//假如我们查询二十个Person对象,在第一次使用到pet时会一次查询出5个pet,对于集合的联系也是如此。
}
}


class Account{
static hasMany = [transactions:Transaction]
//Transaction transaction
Date created

static mapping = {
transactions batchSize: 4
}
}
class Transaction{
static belongsTo = [account:Account]
Date date
}


def c = Account.createCriteria()

def results = c.list {
}

results.each {
println it.transactions
}

在这里会查询出4个transactions集合,SQL语句有可能是:

select
this_.id as id78_0_,
this_.version as version78_0_,
this_.created as created78_0_
from
account this_

select
transactio0_.account_id as account3_1_,
transactio0_.id as id1_,
transactio0_.id as id81_0_,
transactio0_.version as version81_0_,
transactio0_.account_id as account3_81_0_,
transactio0_.date as date81_0_
from
transaction transactio0_
where
transactio0_.account_id in (
?, ?, ?, ?
)

3.约束
Grails的属性(包括many to one / one to one的关联)默认是不为空的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值