Hibernate:createQuery在没有活动事务的情况下无效 [英] Hibernate: createQuery is not valid without active transaction
问题描述
我的Spring + Hibernate项目存在一些问题。当我尝试获取数据时,我有:
HTTP状态500 - 请求处理失败;嵌套异常是org.hibernate.HibernateException:如果没有活动事务,createQuery是无效的
这里是我的xml配置代码:
< beans xmlns =http://www.springframework.org/schema/beans
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns: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 =dataSourceclass =org.apache.commons.dbcp.BasicDataSource
destroy-method =close>
< property name =driverClassNamevalue =com.mysql.jdbc.Driver/>
< property name =urlvalue =jdbc:mysql:// localhost:3306 / users/>
< property name =usernamevalue =root/>
< property name =passwordvalue =12345/>
< / bean>
< bean id =SessionFactory
class =org.springframework.orm.hibernate4.LocalSessionFactoryBean>
< property name =dataSourceref =dataSource/>
< property name =annotatedClasses>
< list>
<值> com.springapp.model.User< /值>
<值> com.springapp.model.UserRole< /值>
< value> com.springapp.model.Project< /值>
< / list>
< / property>
< property name =hibernateProperties>
<道具>
< 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>
< /道具>
< / property>
< / bean>
< tx:注解驱动的事务管理器=transactionManager/>
< bean id =transactionManagerclass =org.springframework.orm.hibernate4.HibernateTransactionManager>
< property name =sessionFactoryref =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();
返回用户;
标记为交易的所有服务。当我删除
< prop key =hibernate.current_session_context_class>线程< / prop>
时有Hibernate错误:当前线程。如何解决此问题?
更新#2
完整版
@Autowired
private SessionFactory sessionFactory;
@SuppressWarnings(unchecked)
public User findByUserName(String username){
List< User> users = new ArrayList< User>();
会话会话= 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();
返回用户;
$现在我有了嵌套异常是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);
返回重定向:/ admin;
}
@RequestMapping(/ admin)
public String adminPanel(ModelMap模型)
{
List< User> users = this.userService.showAllUsers();
model.addAttribute(users,users);
返回adminpanel;
}
解决方案添加
session.beginTransaction();
创建查询之前。
So:
列表< User> users = new ArrayList< User>();
Session session = this.sessionFactory.getCurrentSession();
session.beginTransaction();
users = session.createQuery(from User)。list();
返回用户;
除了编辑
这意味着您尝试启动一个事务,而您没有提交或回滚另一个事务。你必须通过使用
session.getTransaction()。commit()来提交会话(最好是关闭会话)。
session.close();
在您的createQuery之后。
将它添加到你的showAllUsers()和findByUserName()中。
祝你好运!
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";
}
解决方案 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!
这篇关于Hibernate:createQuery在没有活动事务的情况下无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!