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的关联)默认是不为空的

你可能感兴趣的:(grails,groovy)