title: Duplicate key value violates unique constraint "x_pkey"
body: <p>We are facing Unique constraint violation issue when concurrent clients are trying to insert data into child table.</p>
  <p>Suppose We have tables below
  1.Users
  user_id, first_name, last_name.
  2.Projects
  project_id project_name and project_description.</p>
  <p>And both are having many-to-many relation ship.</p>
  <p>When two clients are trying to create a new users. Suppose client1 created user1(id=aa1),child record project(id=1).Client2 also created user2(id=aa2), child record is project(id=1). When two clients concurrently saving record user1, and child also inserting and while second client is trying as project(id-1) already available, it is throwing unique key constraint violation.</p>
  <p>We are checking findby(projectx) before associating child record.</p>
  <p>We are facing this issue rarely. We have implemented retry operation when we have an exception. Even with retry operation issue is not resolving consistently. Please guide me on this.</p>
  <p>Exception is:
  HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement.
  ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (ForkJoinPool.commonPool-worker-1) ERROR: duplicate key value violates unique constraint &quot;x_key&quot;</p>
  <p>We are using this sample code.</p>
  <pre><code>@Entity
  @Table(name = &quot;tbl_users&quot;, schema = &quot;abcd&quot;)
  public class user implements Serializable {
      private static final long serialVersionUID = -8153443692098431986L;
      @Id
      @Column(name = &quot;userId&quot;, nullable = false)
      private String userid;
  
      @Column(name = &quot;last_name&quot;, nullable = false)
      private String lastName;
  
      @Column(name = &quot;first_name&quot;, nullable = false)
      private String firstName;
  
      @ManyToMany(mappedBy = &quot;projectsSet&quot;, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
      private Set&lt;Project&gt; projectsSet;
  }
  
  @Entity
  @Table(name = &quot;tbl_projects&quot;, schema = &quot;abcd&quot;)
  public class Project implements Serializable {
  
      private static final long serialVersionUID = -8153443692098431986L;
      @Id
      @Column(name = &quot;project_id&quot;, nullable = false)
      private String projectId;
  
      @Column(name = &quot;project_Name&quot;, nullable = false)
      private String projectName;
  
      @Column(name = &quot;projectDescription&quot;, nullable = false)
      private String projectDescription;
  
      @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.LAZY)
      @JoinTable(name = &quot;users_projects&quot;, schema = &quot;abcd&quot;, joinColumns = {@JoinColumn(name = &quot;_projectId&quot;)},
              inverseJoinColumns = {@JoinColumn(name = &quot;_userId&quot;)})
      private Set&lt;User&gt; usersSet;
  
  }
  
  @Transactional
  public void saveProject(ProjectDTO projectDTO, Set&lt;UserDTO&gt; userDTOSet) {
      Optional&lt;Project&gt; optionalProject = getProjectFromDB(projectDTO.getProjectId());
      List&lt;User&gt; existUsers = null;
  
      if (!optionalProject.isPresent()) {
  
          Map&lt;String, UserDTO&gt; userDTOMap = userDTOSet.stream().collect(Collectors.toMap(UserDTO::getUserId, userDTO -&gt; userDTO));
          if (MapUtils.isNotEmpty(userDTOMap)) {
              existingUsers = getUsersFromDB(userDTOMap.keySet());
          }
          Project project = new Project();
          try {
              BeanUtils.copyProperties(project, projectDTO)
              updateExistingUsers(project, userDTOMap, existingUsers);
              addNewUsers(project, userDTOMap);
          } catch (IllegalAccessException e) {
              throw new BeanCopyException(&quot;Exception raised while copying the data&quot;, e);
          } catch (InvocationTargetException e) {
              throw new BeanCopyException(&quot;Exception raised while copying the data&quot;, e);
          }
  
          try {
              ProjectRepository.save(user);
          } catch (Exception e) {
  
              throw new CustomException(&quot;Exception raised while saving the new Project&quot;, e);
          }
  
      }
  
  
      private void updateExistingUsers (Project
      newProject, Map &lt; String, UserDTO &gt; newUsers, List &lt; User &gt; existingUsers){
          if (CollectionUtils.isNotEmpty(existingUsers)) {
              existingUsers.stream().forEach(existinguser -&gt; {
                  newProject.addNewUser(existinguser);
                  newUsers.remove(existinguser.getUserId());
              });
          }
      }
  
  
      private void addNewUsers(Project newProject, Map &lt; String, UserDTO &gt; userDTOMap){
          userDTOMap.values().stream().forEach(userDTO -&gt; {
              User user = convertToModel(userDTO);
              newProject.addNewUser(newUser);
          });
      }
  </code></pre>