Logic Controller:Come risolvere StaleObjectStateException con JPA e Hibernate
def updateObject() {
Object o = Object.get(params.id as Long)
o.otherObjects.clear()
objectDataService.saveObject(o.id)
OtherObject newObject = new OtherObject;
o.addToOtherObjects(newObject)
objectDataService.saveObject(o.id)
}
ServiceLogic
def saveObject(long profileId) {
o.save(flush:true)
}
cosa succede
nel 90% dei casi questo sarà solo di lavoro.
problemi
ERROR errors.GrailsExceptionResolver - StaleObjectStateException occurred when processing request: [GET] /controller/updateObject - parameters:
stuff[]: data
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.path.Object#1].
Stacktrace follows:
Message: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.path.Object#1]
Ho letto attraverso domande relative ed ha trovato le merge
chiamata che vedete qui sopra. ha risolto circa il 50% dei casi, ma non tutti.
non sarebbe meglio qui se si spostava questa logica in un metodo di servizio in modo che fosse tutto fatto con la stessa transazione? –
Non voglio sovraccaricare il servizio. pensi che avrebbe senso? –
È sempre meglio spostare la logica di business sui servizi e rendere i controller più sottili possibile (per sottigliezza intendo con meno linee di codice). Ciò ti aiuterà a riutilizzare il codice ovunque richiesto e a risparmiare molto tempo anche nei test. –