title: Violation of PRIMARY KEY With User Registration in Authorization Server
body: <p>A simple application is created by using <code>oauth2 password</code> flow. The Authorization Server is working as the identity provider and when a new user is registered then the <code>jwt</code> token should be received as a response.</p>
  <h2>Relationships between entities</h2>
  <p>User (M) ------------------  Role (M)</p>
  <p>Role (M) ------------------  Permission (M)</p>
  <p>when I signup with a new user the following error has thrown</p>
  <pre><code>Caused by: java.sql.SQLSyntaxErrorException: ORA-02275: such a referential constraint already exists in the table
  </code></pre>
  <p><strong>How can I resolve the primary key violation with JPA? If I use Native Hibernate API then we can use <code>session.merge()</code> but in JPA there is no option like that.</strong></p>
  <h2>Request</h2>
  <pre><code>{
      &quot;userName&quot;: &quot;Nafaz Benzema&quot;,
      &quot;password&quot;: &quot;stackoverflow&quot;,
      &quot;email&quot;: &quot;benz@gmail.com&quot;,
      &quot;active&quot;: &quot;y&quot;,
      &quot;accNonExpired&quot;: &quot;y&quot;,
      &quot;credentialNonExpired&quot;: &quot;y&quot;,
      &quot;accNonLocked&quot;: &quot;y&quot;,
      &quot;roles&quot; : [
          {
              &quot;id&quot;: 101,
              &quot;name&quot;: &quot;ROLE_USER&quot;,
              &quot;permissions&quot;: [
                  {
                      &quot;id&quot;: 10,
                      &quot;name&quot;: &quot;CAN_CREATE&quot;
                  },
                  {
                      &quot;id&quot;: 40,
                      &quot;name&quot;: &quot;CAN_READ&quot;
                  }
              ]
  
          },
           {
              &quot;id&quot;: 102,
              &quot;name&quot;: &quot;ROLE_ADMIN&quot;,
              &quot;permissions&quot;: [
                  {
                      &quot;id&quot;: 10,
                      &quot;name&quot;: &quot;CAN_CREATE&quot;
                  },
                  {
                      &quot;id&quot;: 40,
                      &quot;name&quot;: &quot;CAN_READ&quot;
                  },
                    {
                      &quot;id&quot;: 20,
                      &quot;name&quot;: &quot;CAN_UPDATE&quot;
                  },
                    {
                      &quot;id&quot;: 40,
                      &quot;name&quot;: &quot;CAN_DELETE&quot;
                  }
              ]
          }
      ]
  }
  </code></pre>
  <h2>Entity classes</h2>
  <p><em>User class</em></p>
  <pre><code>@Entity
  @Table(name = &quot;USER90&quot;,schema = Schema.TESTDB,uniqueConstraints = {
          @UniqueConstraint(name = &quot;userName&quot;,columnNames = &quot;USER_NAME&quot;),
          @UniqueConstraint(name = &quot;email&quot;,columnNames = &quot;EMAIL&quot;)
  })
  @Getter
  @Setter
  public class User {
  
      @Id
      @SequenceGenerator(name = &quot;USER_ID_GEN&quot;,sequenceName = Schema.TESTDB+&quot;.USER_ID_SEQ&quot;,initialValue = 1003,allocationSize = 1)
      @GeneratedValue(generator = &quot;USER_ID_GEN&quot;,strategy = GenerationType.SEQUENCE)
      @Column(name = &quot;USER_ID&quot;)
      private int userId;
      @Column(name = &quot;USER_NAME&quot;,nullable = false)
      private String userName;
      @Column(name = &quot;PASSWORD&quot;,nullable = false)
      private String password;
      @Column(name = &quot;EMAIL&quot;,nullable = false)
      private String email;
      @Column(name = &quot;ACTIVE&quot;,nullable = false)
      private String active;
      @Column(name = &quot;ACC_NON_EXPIRED&quot;)
      private String accNonExpired;
      @Column(name = &quot;CREDENTIAL_NON_EXPIRED&quot;)
      private String credentialNonExpired;
      @Column(name = &quot;ACC_NON_LOCKED&quot;)
      private String accNonLocked;
  
      @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
      @JoinTable(name = &quot;USER_ROLE&quot;,joinColumns = {@JoinColumn(name = &quot;USER_ID&quot;, referencedColumnName = &quot;USER_ID&quot;)},
      inverseJoinColumns = {@JoinColumn(name = &quot;ROLE_ID&quot;,referencedColumnName = &quot;ID&quot;)})
      private Set&lt;Role&gt; roles;
  }
  </code></pre>
  <p><em>Role class</em></p>
  <pre><code>@Entity
  @Table(name = &quot;ROLE&quot;,schema = Schema.TESTDB,uniqueConstraints = {
          @UniqueConstraint(name = &quot;name&quot;,columnNames = &quot;NAME&quot;)
  })
  @Getter
  @Setter
  public class Role {
  
      @Id
      @Column(name = &quot;ID&quot;)
      private long id;
      @Enumerated(EnumType.STRING)
      @Column(name = &quot;NAME&quot;)
      private ERole name;
  
      // bi-directional
     /* @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
      private Set&lt;User&gt; users;*/
  
      // uni-directional
      @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
      @JoinTable(name = &quot;PERMISSION_ROLE&quot;,joinColumns = {@JoinColumn(name = &quot;ROLE_ID&quot;,referencedColumnName = &quot;ID&quot;)},
      inverseJoinColumns = {@JoinColumn(name = &quot;PERMISSION_ID&quot;,referencedColumnName = &quot;ID&quot;)})
      private Set&lt;Permission&gt; permissions;
  }
  </code></pre>
  <p><em>Permission class</em></p>
  <pre><code>@Entity
  @Table(name = &quot;PERMISSION&quot;,schema = Schema.TESTDB,uniqueConstraints = {
          @UniqueConstraint(name = &quot;name&quot;,columnNames = &quot;NAME&quot;)
  })
  @Getter
  @Setter
  public class Permission {
  
      @Id
      @Column(name = &quot;ID&quot;)
      private long id;
      @Enumerated(EnumType.STRING)
      @Column(name = &quot;NAME&quot;)
      private EPermission name;
  
  }
  </code></pre>
  <p><strong>Service class</strong></p>
  <pre><code>public Response userRegistration(SignupRequest signup) {
  
  
          if(!Objects.isNull(userDAO.findUserByEmail(signup.getEmail()).orElse(null)))
              throw new UserIsExistedException(String.format(&quot;User is existed with %s&quot;,signup.getEmail()));
  
         try {
              User user=new User();
  
              String password=&quot;{bcrypt}&quot;;
  
             password = password.concat(BCrypt.hashpw(signup.getPassword(),BCrypt.gensalt(12)));
  
  
              user.setUserName(signup.getUserName());
              user.setEmail(signup.getEmail());
              user.setPassword(password);
              user.setActive(&quot;y&quot;);
              user.setAccNonExpired(&quot;y&quot;);
              user.setCredentialNonExpired(&quot;y&quot;);
              user.setAccNonLocked(&quot;y&quot;);
              user.setRoles(signup.getRoles());
  
  
             Set&lt;Role&gt; roles = new HashSet&lt;&gt;();
  
              user.getRoles().forEach(role-&gt;{
                   roles.add(role);
                  Set&lt;Permission&gt; permissions=new HashSet&lt;&gt;();
  
                  role.getPermissions().forEach(perm-&gt;{
                      permissions.add(perm);
                  });
  
                  role.setPermissions(permissions);
  
              });
  
             user.setRoles(roles);
  
             userDAO.save(user);
  
  
              LOGGER.info(&quot;user is saved and response is returned successfully&quot;);
             return new Response(user.getEmail(), authenticationProvider.obtainToken(user.getEmail(), user.getPassword()).toString());
  
          }catch (NumberFormatException ex){
              LOGGER.error(&quot;NumberFormat Exception&quot;);
              throw new NumberFormatException(&quot;NumberFormat Exception&quot;);
          }
          catch (Exception ex){
              LOGGER.error(&quot;invalid username or password&quot;);
             throw new BadCredentialsException(&quot;invalid username or password&quot;,ex);
          }
      }
  </code></pre>
  <p>Note - <strong>If you need more resource here GitHub link</strong></p>
  <p><a href="https://github.com/Benzeman97/identity-provider" rel="nofollow noreferrer" title="click the URL">github_link</a></p>
  <p><strong>config file</strong></p>
  <pre><code>spring:
    datasource:
      url: jdbc:oracle:thin:@localhost:1521:orcl
      username: TESTDB
      password: 14292
      driver-class-name: oracle.jdbc.OracleDriver
    jpa:
      database-platform: org.hibernate.dialect.Oracle10gDialect
      hibernate:
        naming:
          physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        ddl-auto: update
  </code></pre>