如何避免在hibernate中插入重复内容

时间:2017-01-20 06:40:30

标签: hibernate

大家好我已经在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)

2 个答案:

答案 0 :(得分:0)

由于您正在使用saveOrUpdate,因此hibernate将在重复记录的情况下触发更新查询。所以你不应该得到一个重复的行

答案 1 :(得分: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();
        }

    }