简体   繁体   中英

Hibernate unidirectional one to many relationship causing duplicates

Hello Programmers

I am facing an issue regarding a save that is done and is creating the following error in the logs:

> javax.faces.FacesException#{Form292VehicleComponent.saveForm292Vehicle(Form292VehicleComponent.form292Vehicle)}:
> org.springframework.dao.DataIntegrityViolationException: Duplicate
> entry '3a35781b-d2f6-46e7-a72b-605557b29cee' for key
> 'accessareaJustifications_ID'; SQL [n/a]; constraint [null]; nested
> exception is org.hibernate.exception.ConstraintViolationException:
> Duplicate entry '3a35781b-d2f6-46e7-a72b-605557b29cee' for key
> 'accessareaJustifications_ID'

I have two entities :

  • Form292Vehicle
  • AccessAreaJustifications

The two are related as follows:

in Form292Vehicle entity:

 @DiffIgnore
 @JsonIgnore
 private List<AccessAreaJustification> accessareaJustifications;

in AccessAreaJustifications, two fields are used to only keep an ID of the Form292Vehicle without any relationship. This means that the Form292Vehicle has a unidirectional one-to-many relationship with the List.

When application is run, a join table containing the Ids of each entity is created

The table keeps all the entities'Ids as one form292Vehicle Id can have many accessJustifications Ids.

The problem is arising when a user: renew the application form and performs a save. ie a duplicate application with a different Id is made and a save is performed.

I think the problem is with the Hibernate mapping. Can I have a solution to this?

Your list probably contains duplicates. Use a Set instead or make sure you have no duplicates

The solution to the error obtained was not corresponding to either List or Set. It was two transactions trying to commit the same entry on the database for the Object accessareaJustifications. This occurs when one transaction lock in an insert while another transaction was performing the same. So when the database commits the transaction, duplicate entry is found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM