title: JPA repository retrieve custom primary key value after save
body: <p>I have an entity class pointing to postgresql table. Below is table structure. The paymentreferencenumber is the PK which is populated by a trigger. id field is the sequence generated field. When i try to save in this table using JPARepository save method it inserts the first record. But after that it fails due to the primary key constraint. Since PK is a string type and generated using trigger I am specifying generator strategy as 'select'. Can anyone help me with this blocker and point me in the right direction. Thanks</p>
  
  <p>Table structure --</p>
  
  <pre><code>custId serial not null,
      paymentreferencenumber varchar(32) not null
          constraint customers1_pkey
              primary key,
      firstname varchar(255),
      lastname varchar(255)
  
  Entity class --
  @Entity
  @Table(name = "customersnew")
  public class Customer implements Serializable {
  
      private static final long serialVersionUID = -1L;
  
  
      @GeneratedValue(generator = "seq")
      @GenericGenerator(name="seq", strategy="sequence", parameters = { @Parameter(name="key", value = "customersnew_custid_seq")})
      @Column(name = "custid")
      private long id;
  
      @Id
      @GeneratedValue(generator = "trigger_generated")
      @GenericGenerator(name="trigger_generated", strategy="select", parameters = { @Parameter(name="key", value = "id")})
      @Column(name = "paymentreferencenumber")
      private String refNum;
  
      @Column(name = "firstname")
      private String firstName;
  
      @Column(name = "lastname")
      private String lastName;
  
  }
  
  --- Controller using JPA save
  
  @RestController
  public class CustomerController {
  
      @Autowired
      CustomerRepository repository;
  
      EntityManagerFactory emf;
  
      public CustomerController(CustomerRepository repository, EntityManagerFactory emf) {
          this.repository = repository;
          this.emf = emf;
      }
  
      @PostMapping("/create")
      public String create(@RequestBody CustomerUI customer){
          // save a single Customer
  
          Customer returnObj = repository.saveAndFlush(new Customer(customer.getFirstName(), customer.getLastName()));
  
          PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
  
          Object retObj = util.getIdentifier(returnObj);
  
          return "Customer is created";
      }
  </code></pre>