Pages

Wednesday, February 4, 2015

Grails bad practice #1: storing domain objects in session variable

I've learnt that storing domain objects in a session variable is a bad practice. I had to refactor some code, and now everything works correctly. Where were problems when i needed to access some domain properties inside a gsp, but those were solved by passing the needed parameters, not the whole domain classes.

I had a controller and a corresponding gsp code block:

def user = session?.user
    def queue = Queue.findById(params.queueId)

    if(queue){
        user.removeFromQueues(queue)
        queue.delete(flush:true)

        flash.message = "deleted queue with id: ${queue.id}"
        redirect(controller:'queue', action:'index')
    }
<g:each in="${session?.user?.queues}">
        <div id="queue">
            ${it.name} id:${it.id}
                <div id='queueButtons'>
                    <g:hiddenField name="queueId" value="${it.id}" /> 
                    <g:link controller='queue' action='delete' params="[queueId: "${it.id}"]">X</g:link>
                </div>
        </div>
    </g:each>
Now i dont save user in session, i save userId in session, and when needed fetch the user in controllers. On gsp where i needed the user domain to get queues, i passed session.queues that was set in a controller after a user fetch session.queues = user.queues.

2 comments:

  1. If you do store the user object in session you could re-attach it to the Hibernate session with one line:

    user?.attach()

    ReplyDelete
    Replies
    1. Hi! Thanks for your comment. Sometimes this attach could be useful, but as i understand now, the best practice would be to keep in session only the minimum required data.

      Delete