title: Persist One to One Relation with Postgres Sequence
body: <p>I'm playing arround with JavaEE in my free time since a few Months </p>
  
  <p>I have 2 Tables in Postgres</p>
  
  <p>Table person</p>
  
  <pre><code>create table person(id bigint primary key default nextval('person_id_seq'), persontype varchar(5), name varchar(50), ERP_id smallint);
  </code></pre>
  
  <p>Table address</p>
  
  <pre><code>create table address (customer_id bigint primary key NOT NULL references person(id), department varchar(50), street varchar(50), plz varchar(10), city varchar(50), country varchar(50));
  </code></pre>
  
  <p>Model person</p>
  
  <pre><code>    public class Person implements Serializable {
  
          @Id
          @SequenceGenerator(
                  name="person_id_seq",
                  sequenceName="person_id_seq",
                  allocationSize=1,
                  initialValue=1
          )
          @GeneratedValue(
                  strategy=GenerationType.AUTO,
                  generator="person_id_seq"
          )
          private Long            id;
  
          private char            personType;
  
          private String          name;
  
          private Long            erp_id;
  
          @OneToOne (cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH})
          @JoinColumn(name="id", insertable=false, updatable=false)
          private Address address;
  
  [...]    
  
      @PrePersist
      public void initializeCustomerId(){
          this.address.setCustomerId(id);
          }
  </code></pre>
  
  <p>Model address</p>
  
  <pre><code>public class Address implements Serializable {
  
      @Id
      @GeneratedValue(
              strategy=GenerationType.AUTO)
      @Column(name="person_id")
      private Long    personId;
      private String  department;
      private String  street;
      private int     plz;
      private String  city;
      private String  country;
  </code></pre>
  
  <p>I've got this solution from <a href="https://blogs.oracle.com/WebLogicServer/entry/ejb3_mapping_of_one-to-one_rel" rel="nofollow">https://blogs.oracle.com/WebLogicServer/entry/ejb3_mapping_of_one-to-one_rel</a></p>
  
  <p>My Problem now... before I persist I need the id which will be generated by the Postgres-Sequence. </p>
  
  <p>My Thought on this: in @PrePersist I could do an </p>
  
  <pre><code>select nextval('person_id_seq');
  </code></pre>
  
  <p>BUT What if there are more Clients who wants to save at the same time!!</p>
  
  <p>So, how could I solve this Issue? Or am I completely wrong on this?</p>
  
  <p>Thanks</p>
  
  <p>Paddie</p>