Reputation: 1562
this is a long question and weird problem that I hope to solve. My client post a JSON object to my server. I save the report and use the id generated for another purpose in my jms, but sometimes getting null id when my add was successful. How can I prevent this?
In my domain
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
}
In my controller, I have
JSONObject json = request.JSON
AddReportService svc = new AddReportService()
def id= svc.addReport(json)
json.put("id",id)
jmsService.send(queue:'msg.new', json.toString())
In my add report service,
JSONObject obj = report
Reports reports = new Reports()
...
reports.save(flush:true)
myid = reports.id
return myid
In my jms,
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)
Upvotes: 2
Views: 5716
Reputation: 65
You are trying to overwrite the id property. Generally Groovy domain class have a default id property. So no need to define the id property. You could access the id property without defining it in the domain class.
Domain class
class A {
String reportImage
Date reportDateTime
}
In Service class
def instance=new A("xxx",new Date())
if(instance.save())
{
return instance.id
}
Upvotes: 0
Reputation: 66069
If the id is null after an insert, it almost certainly means the insert failed in some way. When you call reports.save()
, you should either add failOnError: true
to or examine the return value.
A few comments on your code:
long
).id = this.id
in the afterInsert
handler does nothing and is unnecessary. GORM makes sure the domain object id is set correctly after an insert.Also, how and when objects get persisted in grails isn't always straightforward, especially if you add in manual flushing and transactions. This is a must read to get a better understanding: http://blog.springsource.com/2010/06/23/gorm-gotchas-part-1/
Upvotes: 4