【问题标题】:Trying to use a grails domain class from the shell尝试从 shell 使用 grails 域类
【发布时间】:2010-03-02 05:19:33
【问题描述】:

我是 Grails 的新手。

我正在尝试从 shell 中使用我的 grails 域,但我无法让它工作。当我运行应用程序时,这些域在脚手架代码中运行良好。

给定这个域类

class IncomingCall {

    String caller_id
    Date call_time
    int  call_length

    static constraints = {
    }
}

我尝试创建一个“IncomingCall”并从 shell 中保存它。无论我做什么,我总是得到“空”;该对象未创建。

如果我尝试创建对象然后保存,我会收到“No hibernate session bound to thread”错误(见下文)。

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> 

如何在 shell 中完成这项工作?

【问题讨论】:

    标签: hibernate spring shell grails groovy


    【解决方案1】:

    我也遇到了这个非常烦人的问题。

    要修复它,请在 shell 中运行此代码以将休眠会话绑定到事务同步管理器:

    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))
    

    完成后,域对象应该按预期工作。

    【讨论】:

      【解决方案2】:

      我发现从 shell 中使用 Grails 域类通常效果不佳。我注意到的一件事是您没有任何导入语句。如果您的类在 com.my.domain 包中,则在尝试创建您需要做的类的实例之前

      import com.my.domain.*
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-17
        • 1970-01-01
        • 2012-05-05
        • 1970-01-01
        • 2011-09-15
        • 2013-02-10
        相关资源
        最近更新 更多