在Grails中使用Insert标志的好处save()

时间:2013-06-21 17:49:49

标签: grails save grails-domain-class

保存域类时使用grails insert标志有什么好处?

这是一个例子: 假设我有一个Domain Object FooBar:

FooBar foo = FooBar.find("foo")?: new FooBar(id:"foo")

foo.bar = "bar"

foo.save()

做更像这样的事情会更好吗?

boolean insertFlag
FooBar foo = FooBar.find("foo")

if(foo == null){
   insertFlag = false
}else {
   foo = new FooBar(id:"foo")
   insertFlag = true
}

foo.bar = "bar"

foo.save(insert: insertFlag)

我认为保存会以某种方式运行得更顺畅,因为插入标志没有它。

1 个答案:

答案 0 :(得分:2)

如果您将域类的insert标识为save,那么generator内的

assigned非常有用。在这种情况下,id必须由用户分配。

这是一种告知hibernate你想要insert一条记录还是只想update的方法。

class FoofBar{
    String bar
    static mapping = {
        id generator: 'assigned'
    }
}

def fooBar = new FooBar(bar: 'foo')
fooBar.id = 100
fooBar.save() //inserts a record with id = 100

def secondFooBar = FooBar.get(100)
secondFooBar.id = 200
//want to insert as a new row instead of updating the old one.
//This forces hibernate to use the new assigned id
fooBar.save(insert: true) 

This会说清楚。