Why am I getting a Primary Key violation for an @OneToMany property?

Since the violation happens in the STUDENT_COURSES table, it seems like you are trying to persist the same relationship twice. You mapped a Set, which signals Hibernate that these relationships must occur not more than once. Check the generated DDL for unique indexes on COURSE_ID, STUDENT_ID).

The reason may be a flaw in your program logic (eg. modifying fields relevant to equals on Courses after they are added to the set or a faulty equals in your Course entity.

You have to decide yourself (your client in the real world, since this is a business decision), if a Student can participate in a Course more than once (e.g. failed the first time).


You have to use GenerationType.TABLE instead of GenerationType.AUTO. That way, jpa uses a sequence table for id assignment and you may never need to generate sequence or auto-increment values or triggers that lowers portability.