2016-06-12 69 views
0

我正在努力使用Hibernate只是为了保存Grails中的用户,没有别的。我找不到这个例子/教程。在Grails服务中注入Hibernate sessionfactory

我不是在寻找GORM,脚手架等WI我试图在我的服务中使用sessionFactory来坚持UserEntity

 def sessionFactory 
     def hibSession = sessionFactory.getCurrentSession() 
     UserEntity userEntity = new UserEntity(); 
     userEntity.setEmail("grails") 
     hibSession.save(userEntity); 
     hibSession.flush() 

但它说sessionFactory为空。

我不清楚如何在我的服务中访问sessionfactory

请指导。

回答

1

编辑2:创建一个集成测试来验证sessionFactory是否被正确注入。运行以下命令的Grails:

create-integration-test <package>.MyService

您可能已经删除了单元测试文件MyServiceSpec.groovy测试/单位目录,如果它的存在。

实现以下测试:

class MyServiceSpec extends Specification { 

    def myService 

    def setup() { 
    } 

    def cleanup() { 
    } 

    void "test something"() { 
     when: 
     def u = myService.serviceMethod() 

     then: 
     u != null 

    } 
} 

你还需要改变你的服务方法返回用户实例,以使测试工作,因为我做了下面。

运行test-app <package.MyService -integration

这是否测试过?如果没有,请提供有关您的开发环境的更多信息。

编辑:在这种情况下可能无所谓,但是您的grails版本/开发环境是什么?在提问时指定它会更好。

首先,你为什么不使用GORM?我没有看到使用grails而没有使用它的核心功能带来的许多好处。为什么你想用sessionFactory来管理ORM而不是GORM?如果你只是打电话给new UserEntity(email:'grails').save(),GORM也会这样做。

这将我引向下一点:您还没有使用Groovy的功能。在Groovy中,您可以像上面那样使用映射构造函数,也可以使用像这样的setter方法:user.email = 'grails'.

此外,调用服务方法后,会话将自动刷新,因此您不需要手动刷新它。但是,这只适用于服务方法是事务性的 - 并且它们是默认的。

我不想阻止你使用Grails,但恕我直言你没有利用Groovy和Grails的强大工具,而是编写Java,Spring和Hibernate。您只能使用惯例,如域类,控制器,视图和服务,我不知道这是否值得。但这是你的选择,你的方法令我惊讶,至少可以说。其次,这是您的代码的工作方式:

MyService。常规:

@Transactional 
class MyService { 

    def sessionFactory 

    UserEntity serviceMethod() { 
     def s = sessionFactory.currentSession 
     def u = new UserEntity(email:'grails') 
     s.save(u) 
     //or: 
     //def user = new UserEntity() 
     //user.email = 'grails' 
     //s.save(user) 
     //or do it the Java way like in your code 

     u.id ? u : null     
    } 
} 

sessionFactory需要被声明为您服务领域,使弹簧能够在启动时命名约定注入它。从你的代码判断,你应该对spring和依赖注入做进一步的阅读。 你可以在the official Spring documentation看看,或者做一步一步首先要了解它,在Tutorialspoint .`

+0

感谢您的详细回答, 其实我使用GWT在我的Grails框架前端 我去通过GORM,但它使用的方式是自动生成视图常规页面等,至少在我发现的教程中,我已经有了GWT视图,我需要从数据库发送一些数据,所以我现在试着做休眠。 我用上面的ur代码,但是它说'sessionFactory'为null。 请指导我为什么我的sessionFactory为空,我是否需要在其他地方定义它,或者我缺少任何东西.. 谢谢 – junaidp

+0

什么是您的Grails版本?你如何测试你的服务代码?我将在我的答案中加入样本集成测试。在单元测试中,bean不是自动装配的。 – nst1nctz

+0

你能解决这个问题吗? – nst1nctz