0

我有以下表格:

标题

---------------------------------
ID             |      STATUS
---------------------------------
1              |        A
---------------------------------
2              |        B
---------------------------------

数据

--------------------------------------------------
ID         |  HEADER_ID    |    DKEY    |   DVALUE
--------------------------------------------------
1          |      1        |    Age     |    90
--------------------------------------------------
2          |      1        |    Gender  |    M
--------------------------------------------------
3          |      1        |    Score   |    1000
--------------------------------------------------
1          |      2        |    Age     |    8
--------------------------------------------------
2          |      2        |    Gender  |    M
--------------------------------------------------
3          |      2        |    Score   |    0
--------------------------------------------------  

我的 JPA 课程是:

**@Entity
@Table (name="HEADER")
public class Header {
    @Id
    @GeneratedValue
    private int id;

    @Column (name="STATUS")
    private String status;

    @OneToMany (cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="header")
    @LazyCollection(LazyCollectionOption.FALSE)
    private Set<Data> dataList;

    --- getters and Setters ---
}


@Entity
@Table (name="DATA")
publi class Data {
    @Id
    @GeneratedValue
    private int id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "HEADER_ID", nullable = false)
    private Header header;

    @Column (name="DKEY")
    private String key;

    @Column (name="DVALUE")
    private String value;
}**

现在,我的问题是,我想使用休眠选择一个“年龄”等于“90”且“性别”等于“M”的数据的标题。我尝试了以下方法:

从 Header h 中选择不同的 h left join h.dataList dl where (dl.key = 'Age' and dl.value = '90') and (dl.key = 'Gender' and dl.value = 'M')

这不会给我任何回报,因为条件“(dl.key = 'Age' and dl.value = '90')和(dl.key = 'Gender' and dl.value = 'M')”在一个“DATA”中执行" 总是会产生错误的记录。

如果我输入或“(dl.key = 'Age' and dl.value = '90')或(dl.key = 'Gender' and dl.value = 'M')”结果是错误的,因为我想获取那些满足年龄和性别条件的 Header。

由于这个问题,我头疼了好几个小时,而且我没有办法再尝试了。希望有人能指出我正确的方向/解决方案。

非常感谢你。

4

1 回答 1

0

您可以尝试这样重写它:

select distinct h from Header as h 
where h.id in 
    (select dl.header.id from Data as dl where dl.key = 'Age' and dl.value = '90') 
and h.id in 
    (select dl.header.id from Data as dl where dl.key = 'Gender' and dl.value = 'M')
于 2013-03-04T18:28:26.733 回答