我试图用Hibernate5创建或更新用户,它抛出以下异常:org。冬眠资源jdbc。内部的LogicalConnectionManagedImpl@779de014关门了
我正在使用以下技术:
这是我的UserDaoImpl。java
:
package com.fasttrack.users.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.fasttrack.users.model.User;
@Repository
@Transactional
public class UserDaoImpl extends AbstractDao implements UserDao
{
@Autowired
private SessionFactory sessionFactory;
public boolean saveUser(User user)
{
Session session=sessionFactory.getCurrentSession();
try
{
session.persist(user);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
finally
{
session.close();
}
}
@SuppressWarnings("unchecked")
public List<User> getUsers()
{
List<User> users;
Session session=sessionFactory.getCurrentSession();
try
{
users=(List<User>) session.createQuery("FROM USER");
return users;
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
session.close();
}
return null;
}
public User getUser(String id)
{
User user;
Session session=sessionFactory.getCurrentSession();
try
{
user=(User)session.get(User.class,id);
return user;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally
{
session.close();
}
}
public boolean updateUser(User user)
{
Session session = sessionFactory.getCurrentSession();
try
{
session.saveOrUpdate(user);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
finally
{
session.close();
}
}
public boolean deleteUserById(String id)
{
User user = new User();
user.setId(id);
Session session = sessionFactory.getCurrentSession();
try
{
session.delete(user);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
finally
{
session.close();
}
}
}
这是我的TestUserDao.java
:
import com.fasttrack.users.dao.UserDao;
import com.fasttrack.users.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/Hibernate-test.xml")
public class TestUserDao
{
@Autowired(required=true)
public UserDao userDao;
@Test
public void testSaveUser()
{
User user=new User();
user.setFirstName("TestUser1");
boolean result=userDao.saveUser(user);
}
}
错误消息:
Mar 01, 2017 1:14:52 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
Mar 01, 2017 1:14:52 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@6be46e8f, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3567135c, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@327471b5, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4157f54e, org.springframework.test.context.transaction.TransactionalTestExecutionListener@90f6bfd, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@47f6473]
Mar 01, 2017 1:14:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Hibernate-test.xml]
Mar 01, 2017 1:14:53 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@2a5ca609: startup date [Wed Mar 01 13:14:53 EST 2017]; root of context hierarchy
Mar 01, 2017 1:14:53 PM org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
INFO: Loading properties file from class path resource [database.properties]
Mar 01, 2017 1:14:53 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Mar 01, 2017 1:14:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.6.Final}
Mar 01, 2017 1:14:53 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 01, 2017 1:14:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 01, 2017 1:14:54 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 01, 2017 1:14:54 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Mar 01, 2017 1:14:54 PM org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource@130d63be] of Hibernate SessionFactory for HibernateTransactionManager
Generated Id: USER0
Mar 01, 2017 1:14:55 PM org.springframework.orm.hibernate5.HibernateTransactionManager doRollbackOnCommitException
SEVERE: Commit exception overridden by rollback exception
java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@6b410923 is closed
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:128)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:79)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:221)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:582)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy31.saveUser(Unknown Source)
at TestUserDao.testSaveUser(TestUserDao.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Hibernatexml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:property-placeholder location="classpath:database.properties" />
<context:component-scan base-package="com.timelee.*" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.timelee.timesheet.model</value>
<value>com.timelee.users.model</value>
<value>com.timelee.*</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
正如Spring框架用户指南中所述,在@Transactional
块中,您不需要手动管理Hibernate会话
,因为TransactionInterceptor
会为您这样做。
所以,而不是:
@SuppressWarnings("unchecked")
public List<User> getUsers() {
List<User> users;
Session session=sessionFactory.getCurrentSession();
try
{
users=(List<User>) session.createQuery("FROM USER");
return users;
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
session.close();
}
return null;
}
你应该这样做:
@SuppressWarnings("unchecked")
public List<User> getUsers() {
try {
return sessionFactory.getCurrentSession()
.createQuery("FROM USER")
.getResultList();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
除了删除会话之外。关闭
call,我在您的示例中修复了更多问题:
Query
上调用getResultList()
,而是将其转换为列表
当我将遗留应用程序更新到Hibernate 5/Spring 4并在其中实现事务支持时,我偶然发现了一个非常相似的堆栈跟踪。
我们使用两个数据库连接(两个SessionFactory和两个TransactionManager)。
问题是我将连接B上的事务嵌套在连接a上的事务中。如下所示:
apiCall -> @Transactional doSomethingWithConnectionA -> @Transactional doSomethingWithConnectionB
当我从同一级别一个接一个地执行这些功能时,问题就消失了
apiCall -> @Transactional doSomethingWithConnectionA -> @Transactional doSomethingWithConnectionB
我在您的错误消息“严重:提交异常被回滚异常覆盖”中发现了一些奇怪的东西。如果查看UserDaoImpl中的try块。Java
文件中有return语句,它在返回之前关闭hibernate连接。您有会话。close()
语句在finally块中,该语句没有意义,因为连接已关闭。您介意删除会话吗。关闭()语句,然后重试。让我知道这是否解决了你的问题。
我需要你帮我把冬眠映射成一对多我不知道为什么这是错的 另一类: 映射 另一个映射: Hibernate配置 这就是错误: 如果有人能帮我,我非常感激,谢谢!
我正在尝试从当前用户那里获取特定租金的列表。 控制器中的代码: account\u id是外键。 运行后,我发现错误: 我做错了什么?
我想写一个简单的不存在的地方子句HQL查询。我不熟悉Hibernate,我有一些小问题。 我的查询如下所示: 我想选择所有包含IDUser当天购买的门票的天数。所有这些都与id为IDFest的节日相关。 我的堆栈跟踪: 映射类: Day.java Festivals.java 门票。Java语言
我尝试打印查询以用于日志记录,我尝试使用ObjectMapper转换org。冬眠查询标准内部的条件对象转换为字符串,但获取序列化错误。任何建议都会有帮助。。 谢谢
初始数据。专业有很多科目。 专业JAVA 对于一个主题来说,专业不能为空。我希望它能以下一种方式工作:当我保存/更新/分离一个主题时,同样的操作必须应用于专业。当我删除一个主题时,专业不会发生任何变化。 主题JAVA 我写了一个集成测试。生成专业()和生成主题()这只是util方法。 你可以在这张图片上看到测试结果。 subjectService在此处引发了异常。保存(主题1); 原因:org。冬
我在Hibernate中使用注释。我得到这个错误: 组织。冬眠MappingException:未知实体:xyz。豆在组织进行测试。冬眠实施。SessionFactoryImpl。位于org的getEntityPersister(SessionFactoryImpl.java:550)。冬眠事件def。DefaultLoadEventListener。org上的onLoad(DefaultLoad