我将如何在休眠状态下一次插入多条记录(使用@Transactional annoation)

时间:2018-05-16 08:07:46

标签: hibernate

我想用hibernate

在时间插入多条记录

我尝试使用以下代码

服务

@Override
    @Transactional
    public boolean addTermdates(FeeTermDates feetermdates) {
        // TODO Auto-generated method stub
        return theMasterDao.addTermdates(feetermdates);
    }

DAO

@Override
    public boolean addTermdates(FeeTermDates feetermdates) {
         boolean success = false;
         try {
                currentSession=sessionFactory.getCurrentSession();

                String stringDate=feetermdates.getDate();

                String val[]=stringDate.split(",");
                for(String date:val)
                {
                    feetermdates.setDate(date);
                    currentSession.save(feetermdates);  
                }


                success=true;
         }  
         catch (Exception e) {  
            e.printStackTrace();
        }
        return success;
    }      

以上代码inserting first record and then updates with last record如下

Hibernate: insert into campus_guru_01.fee_term_dates (date, term_id, tdm_id) values (?, ?, ?)
Hibernate: update campus_guru_01.fee_term_dates set date=?, term_id=? where tdm_id=?

我不想更新我想插入所有记录。

如何实现呢? 请任何人帮助我。

修改 即使我尝试使用merge但没有工作

@Override
    public boolean addTermdates(FeeTermDates feetermdates) {

        int termid=feetermdates.getFeeTerms().getTermId();
        FeeTerms feeTerms=new FeeTerms();
        feeTerms.setTermId(termid);
         boolean success = false;
         try {
                currentSession=sessionFactory.getCurrentSession();

                String stringDate=feetermdates.getDate();
                FeeTermDates feeDate=null;
                String val[]=stringDate.split(",");
                for(String date:val)
                {
                    feeDate=new FeeTermDates();
                    feeDate.setFeeTerms(feeTerms); 
                    feeDate.setDate(date);
                    currentSession.merge(feeDate);    
                }  


                success=true;  
         }  
         catch (Exception e) {  
            e.printStackTrace();
        }
        return success;
    }    

它提供以下异常

Hibernate: insert into campus_guru_01.fee_term_dates (date, term_id, tdm_id) values (?, ?, ?)
Hibernate: update campus_guru_01.fee_term_dates set date=?, term_id=? where tdm_id=?
org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException: Object of class [com.rasvek.cg.entity.FeeTermDates] with identifier [0]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.rasvek.cg.entity.FeeTermDates#0]
    at org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:280)
    at org.springframework.orm.hibernate5.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:755)
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:594)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:765)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:734)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:518)
    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.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy1158.addTermdates(Unknown Source)
    at com.rasvek.cms.controller.MasterController.addTermdates(MasterController.java:600)
    at com.rasvek.cms.controller.MasterController$$FastClassBySpringCGLIB$$c2eff8c2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at com.rasvek.cms.controller.MasterController$$EnhancerBySpringCGLIB$$fe737654.addTermdates(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.rasvek.cg.entity.FeeTermDates#0]
    at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:2400)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3202)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3076)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3477)
    at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:145)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:600)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:474)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1436)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3206)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2412)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:582)
    ... 61 more

1 个答案:

答案 0 :(得分:0)

您正在feetermdates周期中保存相同的for each

我假设它正确保存了第一个feetermdates并立即将插入查询发送到db,对于下一个值,它更新已经保存的一个并再次调用save(它什么都不做)。

在方法结束时,hibernate检查已保存的实体并查看它是否有更新的字段并正确发出更新查询。

你应该做的是创建一个你想要保存的对象的新范围。

String val[]=stringDate.split(",");
Feetermdates feetermdates;
for(String date:val) {
    feetermdates = new Feetermdates();
    feetermdates.setDate(date);
    currentSession.save(feetermdates);  
}

编辑:我说错误地说,为已经管理的实例调用save什么都不做。

它实际上会触发merge,这会通过执行冗余操作来影响性能