title: How to check if username already exists in table?
body: <p>I have the REST API app and when I create a user with the same username it creates all the time, but I want the username to be unique cause in real apps username is unique for each user, how can I provide a checking username in DB?
  I want my app to throw some message when I create a user with a username that already exists, and of course, do not save a new user  username that already exists</p>
  <p>My user Entity:</p>
  <pre><code>@Table(name = &quot;usr&quot;, uniqueConstraints=
  @UniqueConstraint(columnNames={&quot;username&quot;, &quot;email&quot;}))
  public class User {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
  
      @Column(name = &quot;username&quot;)
      private String username;
  
      @Column(name = &quot;password&quot;)
      private String password;
  
      @Column(name = &quot;first_name&quot;)
      private String firstName;
  
      @Column(name = &quot;last_name&quot;)
      private String lastName;
  
      @Column(name = &quot;role&quot;)
      private Role role;
  
      @Column(name = &quot;email&quot;)
      private String email;
  
      @Column(name = &quot;status&quot;)
      private Status status;
  
  //    @OneToMany(mappedBy = &quot;author&quot;)
  //    private List&lt;Message&gt; messages;
  
  //    @OneToMany(mappedBy = &quot;author&quot;)
  //    private List&lt;Comment&gt; comments;
  
      @OneToOne
      @JoinColumn(name = &quot;gender_id&quot;)
      private Gender gender;
  
      @OneToOne
      @JoinColumn(name = &quot;address_id&quot;)
      private Address address;
  
      @ManyToMany
      @JoinTable(
              name = &quot;user_subscriptions&quot;,
              joinColumns =  @JoinColumn(name = &quot;channel_id&quot;) ,
              inverseJoinColumns =  @JoinColumn(name = &quot;subscriber_id&quot;))
      private Set&lt;User&gt; subscribers;
  
      @ManyToMany
      @JoinTable(
              name = &quot;user_subscriptions&quot;,
              joinColumns =  @JoinColumn(name = &quot;subscriber_id&quot;) ,
              inverseJoinColumns =  @JoinColumn(name = &quot;channel_id&quot;))
      private Set&lt;User&gt; subscriptions;
  
      @OneToOne
      @JoinColumn(name = &quot;file_id&quot;)
      private FileEntity fileEntity;
  </code></pre>
  <p>My user service:</p>
  <pre><code>@Transactional
      public User save(UserRequest user) {
          provideAllUserCheckingActionsForSave(user);
          User userUntilSave = userMap.userRequestToUser(user,Role.USER,Status.ACTIVE);
          userUntilSave.setPassword(passwordEncoder.encode(userUntilSave.getPassword()));
          User saved = userRepo.save(userUntilSave);
          log.info(&quot;User save method invoked&quot;);
          return saved;
      }
  </code></pre>