【问题标题】:Hibernate: createQuery is not valid without active transaction休眠:createQuery 在没有活动事务的情况下无效
【发布时间】:2015-10-19 03:33:14
【问题描述】:

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

HTTP 状态 500 - 请求处理失败;嵌套异常是 org.hibernate.HibernateException: createQuery is not valid without active transaction 这是我的 xml 配置代码:

<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;
}

标记为事务的所有服务。当我删除 &lt;prop key="hibernate.current_session_context_class"&gt;thread&lt;/prop&gt; 我有休眠错误:没有为当前线程找到会话。我该如何解决这个问题?

更新 #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:会话已经关闭” 怎么了?

更新 我就是这样称呼这个方法的:

@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";
}

【问题讨论】:

  • 你已经正确配置了 TransactionManager ,但是你为什么不使用它呢?也从 SessionFactory 配置中删除行 thread 因为您希望当前会话由 spring 管理。让你的代码工作添加@Transactional到你的方法或你的服务类

标签: java spring hibernate spring-mvc


【解决方案1】:

创建会话对象时,使用:

Session session = this.sessionFactory.openSession();

而不是

Session session = this.sessionFactory.getCurrentSession();

【讨论】:

    【解决方案2】:

    添加

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

    祝你好运!

    【讨论】:

    • 和之前的 session.openSession();除非您已经有一个打开的会话,这是不好的做法,因为当您从数据库获取/更新数据时,您应该打开然后关闭会话
    • 是的。我以为他只提供了他的代码的 sn-p,我没有注意到返回。
    • 现在当我尝试 'public void addUser(User user){ Session session = this.sessionFactory.getCurrentSession();会话.保存(用户); }' 有错误 org.hibernate.TransactionException:不支持嵌套事务@DriesVD
    • 您能否用新问题和代码/错误编辑您的原始帖子。您发布的评论很难为您提供帮助。
    • 完成!我希望你能帮助我@DriesVB
    猜你喜欢
    • 2023-04-05
    • 2016-05-19
    • 2018-12-31
    • 1970-01-01
    • 2016-08-20
    • 2015-05-12
    • 2014-08-19
    • 1970-01-01
    • 2016-04-25
    相关资源
    最近更新 更多