views:

60

answers:

2

I'm new to Grails.

I'm trying to experiement with my grails domains from the shell, and I can't get it to work. These domains work fine from the scaffold code when I run the app.

Given this domain class

class IncomingCall {

    String caller_id
    Date call_time
    int  call_length

    static constraints = {
    }
}

I try to create an "IncomingCall" and save it from the shell. No matter what I do, I always get "Null"; the object isn't created.

And if I try to create the object and then do a save, I get the "No hibernate session bound to thread" error (see below).

groovy:000> new IncomingCall(caller_id:'555-1212', call_time: new Date(), call_length:10).save()
ERROR org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
        at org.springframework.orm.hibernate3.SpringSessionContext.currentSession (SpringSessionContext.java:63)
        at org.hibernate.impl.SessionFactoryImpl.getCurrentSession (SessionFactoryImpl.java:574)
        at groovysh_evaluate.run (groovysh_evaluate:3)
    ...
groovy:000> 

How can I make this work from the shell?

+1  A: 

I've found that using Grails domain classes from the shell usually doesn't work well. One thing i notices is that you don't have any import statements. If your classes are in package com.my.domain before trying to create and instance of the class you need to do

import com.my.domain.*
Jared
+1  A: 

I ran into this highly annoying problem as well.

To fix it, run this code in the shell to bind the hibernate session to the transaction synchronization manager:

import org.hibernate.Session
import org.hibernate.SessionFactory
import org.springframework.orm.hibernate3.SessionFactoryUtils
import org.springframework.orm.hibernate3.SessionHolder
import org.springframework.transaction.support.TransactionSynchronizationManager
sessionFactory = ctx.getBean("sessionFactory")
session = SessionFactoryUtils.getSession(sessionFactory, true)
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session))

After that's done, domain objects should work as expected.

ataylor