简体   繁体   中英

Java: JPA Entity @OneToMany

how to build the entity X & its relationship to P in this scenario? and annotation use?

Entity P, it has 1 PT and xs (list of x).

@Entity
public class P {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToOne
    @JoinColumn(name = "pt_id")
    private PT pt;

    @OneToMany
    private List<X> xs;

    ...
}

@Entity
public class PT {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
}

xs is a filtered ST list based on PTST (link table of ST & PT), and left join P's values stored in PV.

Table PV, it has p_id, st_id, val.

example:

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

expected output:

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

currently i'm using below query to get data

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

then output

p_id: 1, st_id: 1   t: A    val: 1a
p_id: 1, st_id: 3   t: C    val: NULL

any advice? thank you.

Update:

the query above is manually retrieve the data for an unclean entity X which i want to automate it (no more native query).

Update2:

@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;
}

Well, it looks to me based on the column names that the ST list is in the PT entity:

@Entity
public class PT {
    @Id 
    private Integer id;
    private String name;

    @ManyToMany
    @JoinTable(name="PTST")
    List<ST> st;

That would create a join table named PTST with the two ID columns in it, but you wouldn't be able to use it as a query the way you are doing with the query you have shown. I suppose you could make an entity with a composite key for the PTST table, and then you would be able to make a JPQL query, but since the query you showed is using named parameters, which I think are only available in JPQL, it seems you already have such an Entity.

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM