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)
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 addfailOnError: trueto or examine the return value.A few comments on your code:
long).id = this.idin theafterInserthandler 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/