title: Duplicate key value violates unique constraint, but it shouldn't [Spring Boot, PostgreSQL]
body: <p><strong>A short description of the code:</strong></p>
  <p>User can create a category. Other users then can see that and other categories. They can then press 'follow' on a category and then they are saved to a database. There is picture bellow which shows how it looks in the DB. Everything works fine up to this point.</p>
  <p>User can create many categories and category can have one owner only.</p>
  <p>Categories can have many followers, User can follow many categories.</p>
  <p><strong>The problem</strong></p>
  <p>However, when user then presses 'follow' on another category (with different category ID and all (see HTML and browser screenshot below)) my program crashes and I get this error (excerpt):</p>
  <pre><code>2020-10-09 20:12:21.526  WARN 25512 --- [io-8080-exec-10] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 23505
  2020-10-09 20:12:21.526 ERROR 25512 --- [io-8080-exec-10] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: duplicate key value violates unique constraint &quot;followed_categories_pkey&quot;
    Detail: Key (user_id, category_id)=(37, 5) already exists.
  2020-10-09 20:12:21.526  INFO 25512 --- [io-8080-exec-10] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
  2020-10-09 20:12:21.529 ERROR 25512 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [followed_categories_pkey]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
  
  org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint &quot;followed_categories_pkey&quot;
    Detail: Key (user_id, category_id)=(37, 5) already exists.
  </code></pre>
  <p>And also indicates that it crashes at:</p>
  <p>(this points to a <code>userService.updateUser(user);</code> in the controller)</p>
  <pre><code>at com.blog.reviewwebsite.controller.CategoryController.followCategory(CategoryController.java:59) ~[classes/:na]
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_252]
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_252]
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_252]
      at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_252]
  </code></pre>
  <p><strong>despite both debugger and html showing that I am passing user_id = 37, category_id = 6.</strong></p>
  <p><strong>However</strong>, if I stop my IDE and start it again (DB still shows first follow, like in the picture) and then I sign in with the same user (same user_id) and press follow on another category, everything works and database gets updated (see picture below).</p>
  <p>Then, if I try to follow yet another category, same crash happens again, I would have to restart IDE for it to work again.</p>
  <p><strong>Goal</strong></p>
  <p>User should be able to follow multiple categories without crashes</p>
  <p><strong>What I have tried</strong> (nothing helped):</p>
  <p>I've tried adding <code>cascade = {CascadeType.PERSIST, CascadeType.MERGE}</code> in the User class.</p>
  <p>Overriding Equals and Hashcode in both entity classes.</p>
  <p><strong>Entities</strong></p>
  <ul>
  <li>User</li>
  </ul>
  <pre><code>@Getter
  @Setter
  @Entity
  @Table(name = &quot;users&quot;)
  public class User implements UserDetails {
  
      //other fields
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = &quot;user_id&quot;)
      private Long id;
  
      //This one is used when a user makes a new category
      @OneToMany(mappedBy = &quot;user&quot;, fetch = FetchType.LAZY)
      private Set&lt;Category&gt; categories;
  
  
      //This one is used when a user follows existing category
      @ManyToMany(fetch = FetchType.EAGER)
      @JoinTable(
              name = &quot;followedCategories&quot;,
              joinColumns = @JoinColumn(name = &quot;user_id&quot;),
              inverseJoinColumns = @JoinColumn(name = &quot;category_id&quot;)
      )
      private Set&lt;Category&gt; followedCategories = new HashSet&lt;Category&gt;();
  }
  </code></pre>
  <ul>
  <li>Category</li>
  </ul>
  <pre><code>@Entity
  @Getter
  @Setter
  @Table(name = &quot;Category&quot;)
  public class Category {
  
      //other fields
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = &quot;category_id&quot;)
      private Long id;
  
      //This one is used when a user makes a new category
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = &quot;id&quot;, nullable = false)
      private User user;
  
      //This one is used when a user follows existing category
      @ManyToMany(mappedBy = &quot;followedCategories&quot;)
      private Set&lt;User&gt; users;
  }
  </code></pre>
  <p><strong>Controller</strong></p>
  <pre><code>@Controller
  @RequestMapping(&quot;/categories&quot;)
  public class CategoryController {
  
      private CategoryService categoryService;
      private UserService userService;
  
      public CategoryController(CategoryService categoryService, UserService userService) {
          this.categoryService = categoryService;
          this.userService = userService;
      }
  
      //other methods
  
      @PostMapping(&quot;/follow/{id}&quot;)
      public String followCategory(@PathVariable Long id, @AuthenticationPrincipal User user) {
          Category category = categoryService.getOneById(id);
          user.getFollowedCategories().add(category);
          userService.updateUser(user);
  
          return &quot;redirect:/categories/all&quot;;
      }
  }
  </code></pre>
  <p><em><strong>Service</strong></em></p>
  <ul>
  <li>UserService</li>
  </ul>
  <pre><code>@Service
  public class UserService implements UserDetailsService {
  
      private UserRepository userRepository;
  
      public UserService(UserRepository userRepository) {
          this.userRepository = userRepository;
      }
  
      //other methods
  
   public User updateUser(User user) {
          return userRepository.save(user);
      }
  }
  </code></pre>
  <ul>
  <li>Category Service</li>
  </ul>
  <pre><code>@Service
  public class CategoryService {
  
      private CategoryRepository categoryRepository;
  
      public CategoryService(CategoryRepository categoryRepository) {
          this.categoryRepository = categoryRepository;
      }
  
      //other methods
  
      public Category getOneById(Long id) {
          return categoryRepository.getOne(id);
      }
  }
  </code></pre>
  <p><strong>Repository</strong></p>
  <ul>
  <li>User Repository</li>
  </ul>
  <pre><code>@Repository
  public interface UserRepository extends JpaRepository&lt;User, Long&gt; {
      Optional&lt;User&gt; findUserByUsername(String username);
  }
  </code></pre>
  <ul>
  <li>Category Repository</li>
  </ul>
  <pre><code>@Repository
  public interface CategoryRepository extends JpaRepository&lt;Category, Long&gt; {
  }
  </code></pre>
  <p><strong>Relevant HTML code (with thymeleaf)</strong></p>
  <pre><code>&lt;div th:each=&quot;category: ${categories}&quot;&gt;
  
  
      &lt;p&gt; Category:
          &lt;span&gt;&lt;a th:href=&quot;@{/reviews/(categoryId=${category.id})}&quot; th:text=&quot;${category.name}&quot;&gt;&lt;/a&gt;
          &lt;span th:text=&quot;${category.user.username}&quot;&gt;&lt;/span&gt;
          &lt;span th:text=&quot;${category.id}&quot;&gt;&lt;/span&gt;
          &lt;/span&gt;
      &lt;/p&gt;
      &lt;form method=&quot;post&quot; th:action=&quot;@{/categories/follow/{id}/(id=${category.id})}&quot;&gt;
          &lt;span&gt;follow&lt;/span&gt;
          &lt;input type=&quot;submit&quot;&gt;
      &lt;/form&gt;
  
  &lt;/div&gt;
  </code></pre>
  <p>How it looks in the browser:</p>
  <p><a href="https://i.stack.imgur.com/S0AFN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S0AFN.png" alt="categories with who created it and category id" /></a></p>
  <p>How DB looks after following once</p>
  <p><a href="https://i.stack.imgur.com/9agji.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9agji.png" alt="enter image description here" /></a></p>
  <p>How DB looks after following once, restarting IDE, and then following another category</p>
  <p><a href="https://i.stack.imgur.com/jKoZb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jKoZb.png" alt="enter image description here" /></a></p>