【问题标题】:Grails + hibernate + controller sessionFactory null object?Grails + hibernate + 控制器 sessionFactory 空对象?
【发布时间】:2013-01-07 17:37:13
【问题描述】:

我不熟悉使用 hibernate 和 grails。我有多个需要保留的 java 对象。为了了解它是如何工作的,我使用了一个简单的员工类示例。它在我的 src/java 中,并带有相应的 xml 映射。我想我需要从我的会话工厂创建一个会话实例,我不知道我做错了什么。我遵循了设置休眠hibernate tut 的教程并尝试将其翻译为grails。有什么想法吗?

package com.turingpages.Matrix.view

import org.springframework.dao.DataIntegrityViolationException
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.codehaus.groovy.grails.commons.ApplicationHolder as AH


class MatrixController {

    def ctx = AH.application.mainContext
    def sessionFactory = ctx.sessionFactory

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

...

    def create() {
        def session = sessionFactory.currentSession
        Transaction tx = null;
        Integer employeeID = null;
        try{
            tx = session.beginTransaction();
            Employee employee = new Employee("fname", "lname", 100);
            employeeID = (Integer) session.save(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return employeeID;
    }

我的堆栈跟踪:

 ERROR errors.GrailsExceptionResolver  - NullPointerException occurred when processing request: [POST] /turingpages/matrix/create
Cannot get property 'currentSession' on null object. Stacktrace follows:
Message: Cannot get property 'currentSession' on null object
    Line | Method
->>   33 | create    in com.turingpages.Matrix.view.MatrixController$$ENvP7skK
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|    195 | doFilter  in grails.plugin.cache.web.filter.PageFragmentCachingFilter
|     63 | doFilter  in grails.plugin.cache.web.filter.AbstractFilter
|   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    722 | run       in java.lang.Thread

【问题讨论】:

    标签: spring hibernate model-view-controller grails orm


    【解决方案1】:

    您没有理由使用 Grails 编写这样的代码。如果你真的需要在控制器中管理事务,你应该这样做。

    def create() {
        Integer employeeID = null;
        Employee.withTransaction { status ->
          Employee employee = new Employee(firstName: "fname", lastName: "lname", noIdea: 100);
          employee.save()
          if (employee.hasErrors()) {
             status.setRollbackOnly()
          }
        }
        return employee.id;
    }
    

    也就是说,像这样处理单个域时,您根本不需要担心:

    def create() {
       Employee employee = new Employee(firstName: "fname", lastName: "lname", noIdea: 100);
       employee.save(flush: true)
       [employee: employee] // generally you want to pass the object back to a view this way
       // deal with errors in the domain on the view
    }
    

    使用Service 类会更好。但这可能是你的家庭作业。

    【讨论】:

    • +1,其实new Employee("fname", "lname", 100)也是错的。
    • 如果我使用该代码,我会在static matrices.Employee.withTransaction() 上得到一个无方法异常。 Employee 是 src/java 中的一个 java 类,我在同一位置有相应的 XML 映射。
    • 这是因为您无法将 Employee 更改为 grails 域,还是因为您认为自己做不到?
    • 我正在尝试将员工作为一个简单的例子来看看它是如何工作的。我已经编写了很多想要保留的 Java 对象。
    • 您应该将其添加到您的问题中。提问时尽可能详细,否则你会得到水晶球般的答案。
    【解决方案2】:

    你需要移动代码

    def ctx = AH.application.mainContext
    def sessionFactory = ctx.sessionFactory
    

    进入方法create(),或替换为

    def sessionFactory
    

    但是,Grails 提供了一个withTransaction 方法以更简单的方式为您服务:

        def create() {
            Employee.withTransaction{ status ->
                Employee employee = new Employee("fname", "lname", 100).save()
                .....
                if (employee.id) {
                    return employee.id
                }
                else {
                   status.setRollbackOnly()
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多