无法使用Hibernate将实体保存到数据库中

时间:2016-12-14 13:45:49

标签: java spring hibernate

我使用Spring 3.3.4和Hibernate 5.1.3,java 1.7和Sql Server DB。我写了一个映射到表的简单类但无法保存它。我得到一个异常,我的ID为空。我预计它会自动生成,但失败了。从Exception我可以看到它希望找到一个序列。但在以前版本的Hibernate中,使用本机生成器可以实现相同的功能,而无需使用序列。它应该仍然可行。以下是我的配置,代码和例外:

配置文件:

    <?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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="url" value="jdbc:jtds:sqlserver://localhost:1433;DatabaseName=webadmin;useCursors=true"/>
        <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
        <property name="username" value="XXX"/>
        <property name="password" value="YYY"/>
        <property name="initialSize" value="5"/>
    </bean>
    <bean id="mySessionFactory" name="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="packagesToScan" value="com.xxxx.common.model"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>
</beans>

我的相关代码片段:

    @Entity(name = "Task")
@Table(name = "task")
public class TaskImpl extends SubmittedTaskImpl implements Task {

    private static final long serialVersionUID = -1711538547188780401L;
    @Id
    @GeneratedValue
    @Column(name = "id")
    private long taskId;

最后我的例外:

    2016-12-14 15:20:58.076 [http-bio-8080-exec-10] ERROR org.hibernate.id.enhanced.TableStructure - could not read a hi value
java.sql.SQLException: Invalid object name 'hibernate_sequence'.
    at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372) ~[jtds-1.3.1.jar:1.3.1]
    at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988) ~[jtds-1.3.1.jar:1.3.1]
    at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421) ~[jtds-1.3.1.jar:1.3.1]
    at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671) ~[jtds-1.3.1.jar:1.3.1]
    at net.sourceforge.jtds.jdbc.MSCursorResultSet.processOutput(MSCursorResultSet.java:943) ~[jtds-1.3.1.jar:1.3.1]
    at net.sourceforge.jtds.jdbc.MSCursorResultSet.cursorCreate(MSCursorResultSet.java:541) ~[jtds-1.3.1.jar:1.3.1]
    at net.sourceforge.jtds.jdbc.MSCursorResultSet.<init>(MSCursorResultSet.java:154) ~[jtds-1.3.1.jar:1.3.1]
    at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:452) ~[jtds-1.3.1.jar:1.3.1]
    at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:1029) ~[jtds-1.3.1.jar:1.3.1]
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96) ~[commons-dbcp-1.4.jar:1.4]
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96) ~[commons-dbcp-1.4.jar:1.4]
    at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:224) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:139) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:412) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669) ~[hibernate-core-5.1.3.Final.jar:5.1.3.Final]
    at com.cyberbit.common.repositories.HarvestTaskManagementRepository.saveTask(HarvestTaskManagementRepository.java:23) ~[HarvestTaskManagementRepository.class:?]
    at com.cyberbit.services.HarvestingTaskManagementService.submitTask(HarvestingTaskManagementService.java:47) ~[HarvestingTaskManagementService.class:?]
    at com.cyberbit.services.HarvestingTaskManagementService$$FastClassBySpringCGLIB$$82836951.invoke(<generated>) ~[HarvestingTaskManagementService.class:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at com.cyberbit.services.HarvestingTaskManagementService$$EnhancerBySpringCGLIB$$74298c8f.submitTask(<generated>) ~[HarvestingTaskManagementService.class:?]
    at com.cyberbit.controllers.HarvestingTaskManagementController.submitTask(HarvestingTaskManagementController.java:44) ~[HarvestingTaskManagementController.class:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_79]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_79]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_79]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_79]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220) ~[spring-web-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) ~[spring-web-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) ~[servlet-api.jar:?]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) ~[servlet-api.jar:?]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) ~[catalina.jar:7.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) ~[catalina.jar:7.0.63]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat7-websocket.jar:7.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) ~[catalina.jar:7.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) ~[catalina.jar:7.0.63]
    at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71) ~[log4j-web-2.7.jar:2.7]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) ~[catalina.jar:7.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) ~[catalina.jar:7.0.63]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) ~[catalina.jar:7.0.63]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) ~[catalina.jar:7.0.63]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) ~[catalina.jar:7.0.63]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) ~[catalina.jar:7.0.63]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) ~[catalina.jar:7.0.63]
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957) ~[catalina.jar:7.0.63]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) ~[catalina.jar:7.0.63]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) ~[catalina.jar:7.0.63]
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) ~[tomcat-coyote.jar:7.0.63]
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620) ~[tomcat-coyote.jar:7.0.63]
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) ~[tomcat-coyote.jar:7.0.63]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [?:1.7.0_79]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [?:1.7.0_79]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-coyote.jar:7.0.63]
    at java.lang.Thread.run(Thread.java:745) [?:1.7.0_79]
2016-12-14 15:20:58.076 [http-bio-8080-exec-10] WARN  org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 208, SQLState: S0002
2016-12-14 15:20:58.077 [http-bio-8080-exec-10] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Invalid object name 'hibernate_sequence'.
2016-12-14 15:20:58.077 [http-bio-8080-exec-10] WARN  org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 16945, SQLState: S1000
2016-12-14 15:20:58.077 [http-bio-8080-exec-10] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - The cursor was not declared.
2016-12-14 15:20:58.077 [http-bio-8080-exec-10] WARN  org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 24000
2016-12-14 15:20:58.077 [http-bio-8080-exec-10] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - The executeQuery method must return a result set.
2016-12-14 15:20:58.105 [http-bio-8080-exec-10] ERROR com.cyberbit.controllers.HarvestingTaskManagementController - An error has occurred
com.cyberbit.common.exceptions.EntityRetrievalFailureDueToInfrastructureException: Error occurred while saving task to DB
    at com.cyberbit.common.repositories.HarvestTaskManagementRepository.saveTask(HarvestTaskManagementRepository.java:25)
    at com.cyberbit.services.HarvestingTaskManagementService.submitTask(HarvestingTaskManagementService.java:47)
    at com.cyberbit.services.HarvestingTaskManagementService$$FastClassBySpringCGLIB$$82836951.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    ...
    at com.cyberbit.services.HarvestingTaskManagementService$$EnhancerBySpringCGLIB$$74298c8f.submitTask(<generated>)
    at com.cyberbit.controllers.HarvestingTaskManagementController.submitTask(HarvestingTaskManagementController.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    ...
Caused by: org.hibernate.exception.SQLGrammarException: error performing isolated work
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:79)
    at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
    at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
    at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:412)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
    at com.cyberbit.common.repositories.HarvestTaskManagementRepository.saveTask(HarvestTaskManagementRepository.java:23)
    ... 52 more
Caused by: java.sql.SQLException: Invalid object name 'hibernate_sequence'.
    at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
    at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988)
    at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421)
    at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671)
    at net.sourceforge.jtds.jdbc.MSCursorResultSet.processOutput(MSCursorResultSet.java:943)
    at net.sourceforge.jtds.jdbc.MSCursorResultSet.cursorCreate(MSCursorResultSet.java:541)
    at net.sourceforge.jtds.jdbc.MSCursorResultSet.<init>(MSCursorResultSet.java:154)
    at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:452)
    at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:1029)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
    at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:224)
    at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46)
    at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:139)
    at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126)
    at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
    at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
    ... 65 more

1 个答案:

答案 0 :(得分:3)

  
    

14:33:10,373 ERROR [org.hibernate.id.enhanced.TableStructure](http - 127.0.0.1-8080-3)无法读取hi值:     java.sql.SQLException:无效的对象名称&#39; hibernate_sequence&#39;。

  
     

原因是代替了IdentityGenerator   虽然我们使用的是正确的,但仍使用SequenceStyleGenerator   MSSQLServerDialect并返回supportsIdentityColumns()= true。   SequenceStyleGenerator尝试查找&#39; hibernate_sequence&#39;   表不存在   通过将代码更改为:

来解决mssql的问题
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public long getId()
{
   return id;
}

在此处查看更多此错误 reported issue