Hibernate& Apache Struts2 - 事务未成功启动

时间:2015-07-09 03:59:04

标签: java hibernate session struts2

我正在尝试了解Hibernate和Apache Struts2并遇到了问题。我一直收到这个错误:

HTTP Status 500 - Transaction not successfully started on line
com.dao.struts.UserSession.list(UserSession.java:58)

Hibernate Helper类:

package com.dao.util;

//imports here

public class HibHelper 
{
    private static SessionFactory sessionFactory = buildSession();
    private static ServiceRegistry serviceRegistry;

    public static SessionFactory buildSession()
    {
        try {
            Configuration config = new Configuration();
            config.configure();

            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
            sessionFactory = config.buildSessionFactory(serviceRegistry);

            return sessionFactory;

        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void close() {
        getSessionFactory().close();
    }
}

UserSession类

package com.dao.struts;

//imports here

public class UserSession extends HibHelper
{
    public Data add(Data user)
    {
        Session session = HibHelper.getSessionFactory().openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();

        session.close();
        return user;
    }

    public Data delete(Long id)
    {
        Session session = HibHelper.getSessionFactory().openSession();
        session.beginTransaction();

        Data user = (Data) session.load(Data.class, id);

        if(user != null)
            session.delete(user);

        session.getTransaction().commit();

        session.close();
        return user;
    }

    public List<Data> list()
    {
        Session session = HibHelper.getSessionFactory().openSession();
        session.beginTransaction();

        List<Data> userList = null;

        try {
            userList = (List<Data>) session.createQuery("from Data").list();

        } catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }

        session.getTransaction().commit();

        session.close();
        return userList;
    }
}

这句话说错误出现在list() UserSession.java这一行的session.getTransaction().commit();方法中:mo它完全正确地添加到数据库中。我似乎无法输出它。我的数据库名称为USERS,表名为dependencies { compile 'com.readystatesoftware.systembartint:systembartint:1.0.3' } 。我究竟做错了什么?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

好像您的事务已经提交到数据库。您是否可以检查事务是否已提交(wasCommitted()),如果不提交?

label.bounds

你是否忘记正确打开/关闭if(!session.getTransaction.wasCommitted()){ session.getTransaction.commit() } 的括号。是不是应该使用下面的代码?

if

从我对这个问题的看法来看,下面的代码应该正常工作

 if(user != null){
            session.delete(user);

        session.getTransaction().commit();
}