Grails何时将一个ID分配给一个对象? [英] When does Grails assign an ID to an object?
问题描述
Grails 2.3.4
应用程序正在使用以下域类连接到Oracle数据库:
class Person {
字符串名称
静态映射= {
id列:PERSON_ID,生成器:sequence, params:[sequence:'person_seq']
}
}
code> PersonController 调用 PersonService
中的方法,并调用 UtilService
。被调用的 UtilService
中的方法有一些逻辑基于这个 Person
对象是新的:
if(personInstance.id == null){...}
我发现的是 personInstance
的 id
属性在调用 UtilService
时分配。
控制器操作调用 PersonService
是 @Transactional
,并且服务没有任何事务配置。
所以,有几个问题:
id
有没有更好的方法来检查对象是否是新的( isAttached()
true
所以这对我不好)
编辑: save()
尚未在 pe上调用rsonInstance
UtilService
是否检查 id
。
<原来,我有一个 findBy
,它正在刷新会话:
utilService.someMethod(Person.findByUsername(username))
现在已经填充了 id
。
通过使用 withNewTransaction
:
def personInstance = Person.withNewSession {Person.findByUsername用户名)}
utilService.someMethod(personInstance)
现在让我进入下一个问题 ...
A Grails 2.3.4
application is connecting to an Oracle database using the following domain class:
class Person {
String name
static mapping = {
id column: "PERSON_ID", generator: "sequence", params: [sequence: 'person_seq']
}
}
The PersonController
makes a call to a method in PersonService
and it makes a call to UtilService
. The method in UtilService
being called has some logic based on wether this Person
object is new:
if (personInstance.id == null) { ... }
What I have found is that the id
property of personInstance
(which is passed through the method calls described above) is assigned when the UtilService
is called.
The controller action calling PersonService
is @Transactional
, and the services do not have any transaction configuration.
So, a couple of questions:
- When is
id
value assigned by GORM (I assumed at insert but that seems wrong)? - Is there a better way of checking if the object is new (
isAttached()
returnstrue
so that's not good for me)?
EDIT: save()
has not been called on the personInstance
when UtilService
does the id
check.
Turns out, I had a findBy
which was flushing the session:
utilService.someMethod(Person.findByUsername(username))
It was at this point that the id
was populated.
Got around it by using withNewTransaction
:
def personInstance = Person.withNewSession { Person.findByUsername(username) }
utilService.someMethod(personInstance)
Which now leads me onto the next question...
这篇关于Grails何时将一个ID分配给一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!