2017-01-20 153 views
0

大家好我都顯示在JSP學生數據,在JSP中所選擇的數據我有數據庫來存儲我寫了下面的代碼在這裏如何避免重複的數據插入到數據庫如何避免重複插入休眠

public void addToPreviousSchoolInfo(String[] studentReferencIDS, 
      String[] studentName, String[] studentclass, 
      double[] studentPercentage, String[] studentObtainedClass) { 

     PreviousClassInformation previousClassInformationDTO=null; 
     Session session = null; 
     Transaction tx = null; 
     try { 
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 
      session = sessionFactory.openSession(); 
      tx = session.beginTransaction(); 


      for (int i = 0; i < studentReferencIDS.length; i++) {    

       previousClassInformationDTO=new PreviousClassInformation(); 
       previousClassInformationDTO.setStudentReferenceID(studentReferencIDS[i]); 
       previousClassInformationDTO.setStudentName(studentName[i]); 
       previousClassInformationDTO.setClassName(studentclass[i]); 
       previousClassInformationDTO.setPercentage(studentPercentage[i]); 
       previousClassInformationDTO.setObtainedClass(studentObtainedClass[i]); 
       session.saveOrUpdate(previousClassInformationDTO); 
      }  

      tx.commit(); 

     } catch (HibernateException he) { 
      he.printStackTrace(); 
      tx.rollback(); 
     } 

    } 

我試圖像這樣

public void addToPreviousSchoolInfo(String[] studentReferencIDS, 
      String[] studentName, String[] studentclass, 
      double[] studentPercentage, String[] studentObtainedClass) { 

     PreviousClassInformation previousClassInformationDTO=null; 
     Session session = null; 
     Transaction tx = null; 
     try { 
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 
      session = sessionFactory.openSession(); 
      tx = session.beginTransaction(); 

      tx.begin(); 
      for (int i = 0; i < studentReferencIDS.length; i++) {    


       Criteria criteria = session.createCriteria(PreviousClassInformation.class); 
        criteria.add(Restrictions.eq("studentReferenceID", studentReferencIDS[i])); 
        criteria.add(Restrictions.eq("className", studentclass[i])); 
        criteria.setProjection(Projections.rowCount()); 
        long count = (Long) criteria.uniqueResult(); 
        session.getTransaction().commit(); 
        if(count != 0){ 
         System.out.println("present"); 
        } 
        else{ 
         previousClassInformationDTO=new PreviousClassInformation(); 
         previousClassInformationDTO.setStudentReferenceID(studentReferencIDS[i]); 
         previousClassInformationDTO.setStudentName(studentName[i]); 
         previousClassInformationDTO.setClassName(studentclass[i]); 
         previousClassInformationDTO.setPercentage(studentPercentage[i]); 
         previousClassInformationDTO.setObtainedClass(studentObtainedClass[i]); 
         session.saveOrUpdate(previousClassInformationDTO); 
        } 
      }  

      tx.commit(); 

     } catch (HibernateException he) { 
      he.printStackTrace(); 
      tx.rollback(); 
     } 

    } 

錯誤

Hibernate: select count(*) as y0_ from previousclassinfo this_ where this_.studentReferenceID=? and this_.className=? 
Hibernate: select max(ID) from previousclassinfo 
Hibernate: select count(*) as y0_ from previousclassinfo this_ where this_.studentReferenceID=? and this_.className=? 
org.hibernate.TransactionException: Transaction not successfully started 
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:127) 
    at com.infonex.sms.daoImpl.classpromotion.ClassProtmotionDAOImpl.addToPreviousSchoolInfo(ClassProtmotionDAOImpl.java:97) 
    at com.infonex.sms.controller.classpromotion.ClassPromotion.promoteStudentsToNextClass(ClassPromotion.java:93) 
    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 com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) 
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) 
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) 
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) 
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) 
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) 
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) 
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) 
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) 
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) 
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) 
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) 
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) 
    at com.infonex.sms.filters.Clickjacking.doFilter(Clickjacking.java:55) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) 
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) 
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) 
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) 
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) 
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) 
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) 
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) 
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) 
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) 
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) 
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) 
    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) 

回答

0

由於您使用saveOrUpdate Hibernate會觸發更新查詢重複記錄的情況。所以,你不應該得到一個重複的行

0
public void addToPreviousSchoolInfo(String[] studentReferencIDS, 
      String[] studentName, String[] studentclass, 
      double[] studentPercentage, String[] studentObtainedClass) { 

     PreviousClassInformation previousClassInformationDTO=null; 
     Session session = null; 
     Transaction tx = null; 
     try { 
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 
      session = sessionFactory.openSession(); 
      tx = session.beginTransaction(); 

      tx.begin(); 
      for (int i = 0; i < studentReferencIDS.length; i++) {   


       Criteria criteria = session.createCriteria(PreviousClassInformation.class); 
        criteria.add(Restrictions.eq("studentReferenceID", studentReferencIDS[i])); 
        criteria.add(Restrictions.eq("className", studentclass[i])); 
        criteria.setProjection(Projections.rowCount()); 
        long count = (Long) criteria.uniqueResult(); 

        if(count != 0){ 

        } 
        else{ 
         previousClassInformationDTO=new PreviousClassInformation(); 
         previousClassInformationDTO.setStudentReferenceID(studentReferencIDS[i]); 
         previousClassInformationDTO.setStudentName(studentName[i]); 
         previousClassInformationDTO.setClassName(studentclass[i]); 
         previousClassInformationDTO.setPercentage(studentPercentage[i]); 
         previousClassInformationDTO.setObtainedClass(studentObtainedClass[i]); 
         session.save(previousClassInformationDTO); 
        } 
      }  

      tx.commit(); 


     } catch (HibernateException he) { 
      he.printStackTrace(); 
      tx.rollback(); 
     } 

    }