繁体   English   中英

尝试从Shell使用Grails域类

[英]Trying to use a grails domain class from the shell

我是Grails的新手。

我正在尝试从shell中尝试我的grails域,但无法使其正常工作。 当我运行应用程序时,这些域可以通过脚手架代码正常运行。

给定该域类

class IncomingCall {

    String caller_id
    Date call_time
    int  call_length

    static constraints = {
    }
}

我尝试创建一个“ IncomingCall”并将其从外壳中保存。 无论我做什么,我总是得到“ Null”; 没有创建对象。

而且,如果我尝试创建对象然后进行保存,则会收到“无休眠会话绑定到线程”错误(请参见下文)。

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进行这项工作?

我发现从外壳程序使用Grails域类通常效果不佳。 我注意到的一件事是您没有任何导入语句。 如果您的类在尝试创建和创建类实例之前位于com.my.domain包中,则需要执行此操作

import com.my.domain.*

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

要解决此问题,请在外壳程序中运行以下代码以将休眠会话绑定到事务同步管理器:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM