保存域类时使用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)
我认为保存会以某种方式运行得更顺畅,因为插入标志没有它。
答案 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会说清楚。