zoran119
zoran119

Reputation: 11307

How to implement a read only controller action

I have an Order domain class (hasMany = [items: Item]) and an edit screen which lets you edit an instance of Order.

The edit screen has the totalCost field which is calculated via ajax as items are added/removed. The backend calculation of totalCost is complex one (cannot be done on the front end, has to be on the back end) and it depends on:

So, to carry out the totalCost calculation, I do something like this:

def ajaxCalculateTotalCost() {
    def order = Order.get(params.id)
    order.properties = params
    def totalCost = // complex calculation based on params.items, logged in user and so on...
    // return totalCost as JSON here
}

The problem with this is that once the ajax call is made to ajaxCalculateTotalCost() the Order instance being edited gets saved. As far as I understand, Spring or Hibernate flushes the session at the end of the HTTP request???

This is a problem as if the user has added/removed items the cannot cancel their changed by clicking Cancel at the bottom of the form (the Order got saved when the ajax call happened).

Can anyone suggest how to carry out the calculation without saving the Order instance?

Upvotes: 0

Views: 717

Answers (2)

James Kleeh
James Kleeh

Reputation: 12228

Do what @saw303 says or do order.discard() to tell Hibernate to not persist that object

Upvotes: 0

saw303
saw303

Reputation: 9082

Use read instead of get.

def order = Order.read(params.id)

and mark the controller action as @Transactional(readOnly=true).

Another option is to move the calculation into a service class and mark the service method @Transactional(readOnly=true)

Upvotes: 2

Related Questions