插入后的Grails实体id
这是一个很长很奇怪的问题,我希望能解决。我的客户端将JSON对象发布到我的服务器。我保存报告并在jms中使用为其他目的生成的id,但有时在添加成功时会获得空id。我怎样才能防止这种情况 在我的领域插入后的Grails实体id,grails,gorm,Grails,Gorm,这是一个很长很奇怪的问题,我希望能解决。我的客户端将JSON对象发布到我的服务器。我保存报告并在jms中使用为其他目的生成的id,但有时在添加成功时会获得空id。我怎样才能防止这种情况 在我的领域 int id String reportImage Date reportDateTime; static constraints = { id(blank:false, unique:true) reportImage (blank:true, nullable:true)
int id
String reportImage
Date reportDateTime;
static constraints = {
id(blank:false, unique:true)
reportImage (blank:true, nullable:true)
reportDateTime (blank:false)
}
def afterInsert = {
id= this.id
}
在我的控制器中,我有
JSONObject json = request.JSON
AddReportService svc = new AddReportService()
def id= svc.addReport(json)
json.put("id",id)
jmsService.send(queue:'msg.new', json.toString())
在我的添加报告服务中
JSONObject obj = report
Reports reports = new Reports()
...
reports.save(flush:true)
myid = reports.id
return myid
在我看来
def jmsService
static transactional = false
static exposes = ['jms']
@Queue(name='msg.new')
def createMessage(msg) {
JSONObject json = new JSONObject(msg)
int id = json.get("id") // sometimes is null, but report was added. How to prevent?
AlertManagement am = new AlertManagement()
am.IsToSendAlert(id)
如果插入后id为null,则几乎可以肯定,这意味着插入以某种方式失败。调用
reports.save()
时,应将failOnError:true
添加到或检查返回值
关于您的代码的一些评论:
- 您不需要在域对象中声明id属性,grails隐式地添加了一个属性(类型为
)long
- 同样,id约束也是冗余的
- 在
处理程序中分配afterInsert
,没有任何作用,也没有必要。GORM确保在插入后正确设置域对象idid=this.id
此外,对象如何以及何时在grails中持久化并不总是简单的,特别是如果您添加了手动刷新和事务。为了更好地理解,必须阅读以下内容:如果插入后id为空,则几乎肯定意味着插入以某种方式失败。调用
reports.save()
时,应将failOnError:true
添加到或检查返回值
关于您的代码的一些评论:
- 您不需要在域对象中声明id属性,grails隐式地添加了一个属性(类型为
)long
- 同样,id约束也是冗余的
- 在
处理程序中分配afterInsert
,没有任何作用,也没有必要。GORM确保在插入后正确设置域对象idid=this.id
此外,对象如何以及何时在grails中持久化并不总是简单的,特别是如果您添加了手动刷新和事务。为了更好地理解,必须阅读以下内容:您正试图覆盖id属性。通常Groovy域类有一个默认的id属性。因此不需要定义id属性。您可以访问id属性,而无需在域类中定义它 域类
class A {
String reportImage
Date reportDateTime
}
服务类
def instance=new A("xxx",new Date())
if(instance.save())
{
return instance.id
}
您正在尝试覆盖id属性。通常Groovy域类有一个默认的id属性。因此不需要定义id属性。您可以访问id属性,而无需在域类中定义它 域类
class A {
String reportImage
Date reportDateTime
}
服务类
def instance=new A("xxx",new Date())
if(instance.save())
{
return instance.id
}