2

I am new to Hibernate (5.2.3.final) and try to use it for a private project to get familiar with it. Database is MariaDB (5.5.53-0070) on a local server, Hibernate dialect is set to "org.hibernate.dialect.MySQL5InnoDBDialect"

In my application, I have the two classes Year and Grade. Each year may contain several grades in an user-defined order. I try to let Hibernate save the order of the list of grades by using @OrderColumn (name="listOrder").
This works well so far, I just have the problem of reordering the list: Whenever I remove an item from the list to insert it at another place in the same list, Hibernate creates an update statement that causes an QueryException.

My test code looks like this:

// grades is the list managed by Hibernate, it contains 4 entries
// here it is received from the first Year entry in the database

List<Grade> grades = ym.getElementAt(0).getGrades();
SessionUtil.beginTransaction();
Grade grade = grades.get(0);
grades.remove(0);  // remove from current position
SessionUtil.flush();        
grades.add(grade);  // add to end of list
SessionUtil.commitTransaction();

During the flush (after removing the element), I get an exception, caused by an update statement:

Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
     [... many lines ...]
Caused by: org.mariadb.jdbc.internal.util.dao.QueryException: Duplicate entry '10' for key 'UK_3o21jcxyfab7r95ikn8at88ih'
Query is: update Year_Grade set grades_id=? where Year_id=? and listOrder=?, parameters [10,1,0]

I understand, that the same grades_id may not exist twice in the same list (or even in any list). I just don't see, why Hibernate does it this way, instead of just updating the listOrder column for the year/grade combination.

In class Year I define the list that contains the Grade objects:

@OneToMany
@OrderColumn(name="listOrder")
private List<Grade> grades = new DataObjectList<Grade>();

public List<Grade> getGrades() {
    return grades;
}

In class Grade I have no variable pointing back to Year, since I always access data in only one direction (from Year to Grade to Subject to ...)

I have already been reading the online documentation on the Hibernate or JBoss website and have used Google for quite some hours now. All advice I found seemed to not cover my problem here.

Could it be the wrong dialect for the database? Did I miss some annotations to set?

Thanks in advance for any help...

upf
  • 96
  • 7
  • Does this answer your question? [Constraint violation in Hibernate unidirectional OneToMany mapping with JoinTable and OrderColumn when removing elements](https://stackoverflow.com/questions/4022509/constraint-violation-in-hibernate-unidirectional-onetomany-mapping-with-jointabl) – C-Otto Mar 24 '21 at 14:05
  • I'm late to the party but have you found a solution to this problem ? – Blockost Apr 12 '22 at 10:57

0 Answers0