title: How to use existing records in many-to-many relation and to avoid unique constraint violation (hibernate)
body: <p>&nbsp;There are two classes, Person and Vehicle, in many-to-many relationship. If a new Person is created or a record of existing Person is updated (e.g. Vehicle records added) it would be desirable to use existing Vehicle record if it exists.</p>
  
  <p>&nbsp;The question is how to achieve it. A query prior the insert or update is not an option because there are many threads which can update or insert.</p>
  
  <p>&nbsp;At this moment the application checks unique constraint exception and when it is caught the new existing Vehicle object is replaced by one which is queried from the db by "registration" column. This solution is working however it seems to be kind of clumsy as there has to be a separate session created for each Vehicle record.</p>
  
  <p>Is there any way how to achieve desired behaviour by hibernate annotations? Or completely different solution? Thanks.</p>
  
  <pre><code>@Entity
  @Table(name="PERSON", uniqueConstraints = { @UniqueConstraint(columnNames = "name", name="NAME_KEY") })
  public class Person  implements Serializable {
    private static final long serialVersionUID = 3507716047052335731L;
  
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="PersonIdSeq")
    @SequenceGenerator( name = "PersonIdSeq", sequenceName="PERSON_ID_SEQ")
    private Long id;
  
    @Index(name="PERSON_NAME_IDX")
    private String name;
  
    @ManyToMany(targetEntity=Vehicle.class, cascade={CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name="PERSON_VEHICLE_LNK", joinColumns=@JoinColumn(name="PERSON_ID"),inverseJoinColumns=@JoinColumn(name="VEHICLE_ID"),
       uniqueConstraints = { @UniqueConstraint(columnNames = {"PERSON_ID", "VEHICLE_ID"}, name="person_vehicle_lnk_key")})
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="PersonVehicleLnkIdSeq")
    @SequenceGenerator(name = "PersonVehicleLnkIdSeq", sequenceName="PERSON_VEHICLE_LNK_ID_SEQ")
    @CollectionId(columns = @Column(name="ID"), type=@Type(type="long"), generator = "PersonVehicleLnkIdSeq")
    private List&lt;Vehicle&gt; vehicle = new ArrayList&lt;&gt;();
    ...
  
  @Entity
  @Table( name = "VEHICLE", uniqueConstraints = {@UniqueConstraint(columnNames="registration", name="REGISTRATION_KEY")}  )
  public class Vehicle implements Serializable {
    private static final long serialVersionUID = -5592281235230216382L;
  
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="VehicleIdSeq")
    @SequenceGenerator( name = "VehicleIdSeq", sequenceName="VEHICLE_ID_SEQ")
    private Long id;
  
    @Index(name="REGISTRATION_IDX")
    private String registration;
    ...
  </code></pre>