title: Java: JPA Entity @OneToMany
body: <p>how to build the entity X &amp; its relationship to P in this scenario? and annotation use?</p>
  
  <p>Entity P, it has 1 PT and xs (list of x).</p>
  
  <pre><code>@Entity
  public class P {
  
      @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
      private int id;
  
      @OneToOne
      @JoinColumn(name = "pt_id")
      private PT pt;
  
      @OneToMany
      private List&lt;X&gt; xs;
  
      ...
  }
  
  @Entity
  public class PT {
      @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
      private int id;
      private String name;
  }
  </code></pre>
  
  <p>xs is a filtered ST list based on PTST (link table of ST &amp; PT),
  and left join P's values stored in PV.</p>
  
  <p>Table PV, it has p_id, st_id, val.</p>
  
  <p>example:</p>
  
  <pre><code>P:
  id    pt_id
  1     1
  2     2
  3     1
  
  PT: 
  id    name
  1     pt-1
  2     pt-2
  
  ST
  id    t
  1     A
  2     B
  3     C
  4     D
  5     E
  
  PTST
  pt_id    st_id
  1        1
  1        3
  2        1
  2        2
  
  PV
  p_id    st_id    val
  1       1        1a
  2       2        2b
  </code></pre>
  
  <p>expected output:</p>
  
  <pre><code>P = 1
  p_id    st_id    st_t    val
  1       1        A          1a
  1       3        C          NULL
  
  P = 2
  p_id    st_id    st_t    val
  2       1        A          NULL
  2       2        B          2b
  </code></pre>
  
  <p>currently i'm using below query to get data</p>
  
  <pre><code>select st.id as st_id, st.t, :p2 as p_id, pv.val
              from PTST ptst 
              inner join ST st on (st.id = ptst.st_id)
              left join PV pv on (pv.p_id = :p1 and pv.st_id = ptst.st_id)
              where PTST.pt_id = :p3
  </code></pre>
  
  <p>then output</p>
  
  <pre><code>p_id: 1, st_id: 1   t: A    val: 1a
  p_id: 1, st_id: 3   t: C    val: NULL
  </code></pre>
  
  <p>any advice? thank you.</p>
  
  <p>Update:</p>
  
  <p>the query above is manually retrieve the data for an unclean entity X which i want to automate it (no more native query).</p>
  
  <p>Update2:</p>
  
  <pre><code>@Entity
  @Table(name = "PV")
  public class X{
  
      @EmbeddedId
      private Y id = new Y();
  
      @Column(updatable = false, insertable = false)
      private String st_t;
      private String val;
  }
  
  
  @Embeddable
  public class Y implements Serializable {
      @Column(updatable = false)
      private int p_id;
      @Column(updatable = false)
      private int st_id;
  }
  </code></pre>