Hibernate: createQuery is not valid without active

2020-03-26 05:55发布

问题:

I have some problems with my Spring + Hibernate project. When i try to fetch data, i have:

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: createQuery is not valid without active transaction Here my code for 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>

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

All services marked as Transactionals. When I delete <prop key="hibernate.current_session_context_class">thread</prop> I have Hibernate error: No Session found for current thread. How can I solve this problem?

UPDATED #2 Full dao

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

Now I have "nested exception is org.hibernate.SessionException: Session was already closed" What's the matter?

UPDATE This is how I called this methods:

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

回答1:

Add

        session.beginTransaction();

Before creating your query. So:

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

Addition to your edit

This means you're trying to start a transaction, while you did not commit or rollback another transaction. You have to commit to your session (and preferably closing the session) by using

session.getTransaction().commit();
    session.close();

After your createQuery. Add it to your showAllUsers() and findByUserName()

Good luck!