java - 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
我将如何检查学生课程列表是否包含指定的课程?
解决方案
推荐阅读
- javascript - Postman - 从 HTML 描述列表中提取值
- php - 检查 isset($_POST["submit"]) 两次不起作用
- flutter - _TypeError(类型'Null'不是'String'类型的子类型)在颤动
- c# - uwp b2c app c#.net app中的querystring is too long错误
- python - 如何在jupyter笔记本中保存离线图形?
- react-native - 使用 M1 在 Mac 上正确设置 react-native(找不到正确答案)
- forms - 谷歌表单和表格
- python - 创建一个检查完美数python的函数
- python - 字符串操作熊猫
- bash - 我想使用用户的输入,然后使用 case 语句调用一个函数