как бы я вставил несколько записей одновременно в спящем режиме (используя аннотацию @Transactional) - PullRequest
0 голосов
/ 16 мая 2018

Я хочу вставить несколько записей одновременно с 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=?

Я не хочу обновлять. Я хочу вставить все записи.

как этого добиться? Пожалуйста, помогите мне с этим.

EDIT даже я пытался с 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 голосов
/ 16 мая 2018

Вы сохраняете тот же feetermdates в этом цикле for each.

Я предполагаю, что он правильно сохранил первый feetermdates и немедленно отправил запрос на вставку в db, для следующего значения он обновляетуже сохранен один и вызовите save на нем снова (что ничего не делает).

В конце режима гибернации проверьте сохраненный объект и убедитесь, что у него есть обновленное поле и правильно выполните запрос на обновление.

То, что вы должны были сделать, - это создать новый экземпляр объекта, который вы хотели сохранить.

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

Редактировать: Я ошибся, сказав, что вызов save дляуже управляемый экземпляр ничего не делает.

На самом деле он запускает merge, что повлияет на производительность, выполняя избыточную операцию

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...