首页 > 解决方案 > JAVA ORM:检查学生是否已注册课程错误代码:1062

问题描述

我在使用这种方法时遇到问题,该方法假设为学生注册他们选择的课程。如果他们已经注册了课程,那么程序将返回一条消息,上面写着“您已经注册了该课程”

public void registerStudentToCourse(String sEmail, int cId) {
        try {
            // open connection manually
            EntityManagerFactory entitymanagerfactory = Persistence.createEntityManagerFactory("SMS4");
            EntityManager entitymanager = entitymanagerfactory.createEntityManager();
            // start a transaction with database
            entitymanager.getTransaction().begin();

            // object of Course
        Course addNewCo = new Course();
        // object of Student
        Student currStu = new Student();
        // list of Course object
        List<Course> sCourse = new ArrayList<Course>();
        // object of StudentServices to use method getStudentByEmail
        StudentService getStu = new StudentService();
        // save Student object to currStu
        currStu = getStu.getStudentByEmail(sEmail);
        // save student courses to sCourse
        sCourse = getStudentCourses(sEmail);
        // get Course selected by user by id and save all the information in object ofd
        // Course
        addNewCo = entitymanager.find(Course.class, cId);
        // add the new course selected by user to the main courses of the student
    
        if (sCourse.contains(entitymanager.find(Course.class, cId))){
            System.out.println("You're already registered in this course");
            return;
        }
        
        
        sCourse.add(addNewCo);
        // add all the information of student info and new courses list
        Student finalStu = new Student(currStu.getsEmail(), currStu.getsName(), currStu.getsPass(), sCourse);
        // merge that data using JPA to database
        entitymanager.merge(finalStu);
        // commit to changes
        entitymanager.getTransaction().commit();
        // close connection
        entitymanager.close();
        entitymanagerfactory.close();
    } catch (NullPointerException e) {
        em.getTransaction().rollback();
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        em.getTransaction().rollback();
        e.printStackTrace();
    }
   
}

当我尝试为学生注册他们已经注册的课程时,我遇到的错误是:

Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'aiannitti7@is.gd-1' for key 'PRIMARY'
Error Code: 1062

我将如何检查学生课程列表是否包含指定的课程?

标签: javaormeclipselink

解决方案


推荐阅读