Hibernate:没有活动事务,createQuery无效

时间:2015-07-28 14:04:40

标签: java spring hibernate spring-mvc

我的Spring + Hibernate项目存在一些问题。当我尝试获取数据时,我有:

HTTP状态500 - 请求处理失败;嵌套异常是org.hibernate.HibernateException:没有活动事务,createQuery无效 这是我的xml config代码:

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/users" />
    <property name="username" value="root"/>
    <property name="password" value="12345"/>
</bean>

<bean id="SessionFactory"
               class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.springapp.model.User</value>
            <value>com.springapp.model.UserRole</value>
            <value>com.springapp.model.Project</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
        </props>
    </property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="SessionFactory"/>
</bean>

来自DAO的方法

@Override
public List<User> showAllUsers(){
    List<User> users = new ArrayList<User>();
    Session session = this.sessionFactory.getCurrentSession();
    users = session.createQuery("from User").list();
    return users;
}

所有标记为交易的服务。当我删除 <prop key="hibernate.current_session_context_class">thread</prop> 我有Hibernate错误:找不到当前线程的会话。我该如何解决这个问题?

更新#2 全道

@Autowired
private SessionFactory sessionFactory;

@SuppressWarnings("unchecked")
public User findByUserName(String username) {

    List<User> users = new ArrayList<User>();

    Session session = this.sessionFactory.getCurrentSession();
    session.beginTransaction();
    users = session
            .createQuery("from User where username=?")
            .setParameter(0, username).list();
    session.getTransaction().commit();
    session.close();
    if (users.size() > 0) {
        return users.get(0);
    } else {
        return null;
    }
}

@Override
public void addUser(User user){
    Session session = this.sessionFactory.getCurrentSession();
    session.save(user);
}

@Override
public void deleteUser(User user){
    Session session = this.sessionFactory.getCurrentSession();
    System.out.println(user.getUsername());
    session.delete(user);
}
@Override
public void verifyUser(User user){
    Session session = this.sessionFactory.getCurrentSession();
    session.update(user);
}
@Override
public List<User> showAllUsers(){
    List<User> users = new ArrayList<User>();
    Session session = this.sessionFactory.getCurrentSession();
    session.beginTransaction();
    users = session.createQuery("from User").list();
    session.getTransaction().commit();
    session.close();
    return users;
}

现在我有“嵌套异常是org.hibernate.SessionException:Session已经关闭” 怎么了?

更新 这就是我称之为这种方法的方法:

@RequestMapping("/admin/updateUser")
public String updateUser(ModelMap model,@ModelAttribute("userId") String username)
{
    User user = this.userService.findByUserName(username);
    if(user.isEnabled()) user.setEnabled(false);
    else user.setEnabled(true);
    this.userService.updateUser(user);
    return "redirect:/admin";
}
 @RequestMapping("/admin")
public String adminPanel(ModelMap model)
{
    List<User> users = this.userService.showAllUsers();
    model.addAttribute("users",users);
    return "adminpanel";
}

2 个答案:

答案 0 :(得分:4)

添加

        session.beginTransaction();

在创建查询之前。 所以:

  List<User> users = new ArrayList<User>();
Session session = this.sessionFactory.getCurrentSession();
session.beginTransaction();
users = session.createQuery("from User").list();
return users;

添加到您的修改

这意味着您尝试启动事务,而您没有提交或回滚另一个事务。您必须使用

提交您的会话(最好是关闭会话)
session.getTransaction().commit();
    session.close();

在你的createQuery之后。 将它添加到showAllUsers()和findByUserName()

祝你好运!

答案 1 :(得分:0)

创建会话对象时,请使用:

Session session = this.sessionFactory.openSession();

代替

Session session = this.sessionFactory.getCurrentSession();