title: Enforcing primary key constraint in Spring JPA
body: <p>I am using Spring JPA backed by an embedded in-memory database, specifically Apache Derby.</p>
  
  <p>Simply put, I have an entity class like this:</p>
  
  <pre><code>@Entity
  public class Person {
  
      @Id
      @NotNull
      @Column(unique = true, updatable = false, name = "PERSON_ID")
      private Long personId;
  
      @NotNull
      @Size(min = 1)
      private String name;
  
      public Person() {
      } 
      //continue....
  </code></pre>
  
  <p>and in a @Service component I have a method like this:</p>
  
  <pre><code>@Autowired
  private PersonRepository personRepository;
  
  @Override
  public void addPerson(Person person)  {
          personRepository.save(movie);
  }
  </code></pre>
  
  <p>where the repository is defined as follows:</p>
  
  <pre><code>public interface PersonRepository extends CrudRepository&lt;Person, Long&gt; { }
  </code></pre>
  
  <p>The <strong>problem</strong> is the following: the primary key constraint is not enforced as I would expect.</p>
  
  <p>More specifically, If I have two Person object with the same key:</p>
  
  <pre><code>Person person1 = new Person(1L, "Johan");
  Person person2 = new Person(1L, "Tom");
  </code></pre>
  
  <p>and I call in sequence the add method:</p>
  
  <pre><code>serviceObject.addPerson(person1);
  serviceObject.addPerson(person2);
  </code></pre>
  
  <p>what will happen is that the <em>personRepository.save(movie)</em> method is going to save a Person with same ID twice, thus overwriting the former record. In the end there is only one Person with that ID, and its name is "Tom". I retrieve a record using the <em>findOne</em> method as follows:</p>
  
  <pre><code>public Person getPersonById(long personId) {
      Person person = personRepository.findOne(personId);
  </code></pre>
  
  <p>However I would have expected the second attempt to fail because of some PrimaryKey Constraint Violation, with the name not being changed from "Johan" to "Tom".</p>
  
  <p><strong>Questions</strong>:</p>
  
  <ul>
  <li>Why this is happening?</li>
  <li>I understand that I could have enforced this rule at the database level. Is this the only way to achieve it? In my case, using Apache Derby, can I achieve this? Or how to enforce at the JPA level the usual primary key constraint so that records with a duplicate key are rejected rather than overwriting the previous one?</li>
  </ul>
  
  <p>P.S.: I am interested into inserting the primary key manually, so <em>@GeneratedValue</em> or any other mechanism that would prevent in principle to pass twice the same key are not an option.</p>