休眠:选择父母与子女条件

时间:2013-03-04 17:07:28

标签: java hibernate jpa

我有以下表格:

标题

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

现在,我的问题是,我想选择一个数据的Header,其中“Age”等于“90”,而“Gender”等于“M”使用hibernate。 我尝试了以下方法:

从标题h中选择不同的h左连接h.dataList dl where(dl.key ='Age'和dl.value ='90')和(dl.key ='Gender'和dl.value = 'M')

这没有给我任何回报,因为条件“(dl.key ='Age'和dl.value = '90')和(dl.key ='Gender'和dl.value ='M')”在一条“DATA”记录总是屈服于假。

如果我放或,“(dl.key ='年龄'和dl.value = '90')或(dl.key ='性别'和dl.value ='M')”结果是错误的我希望得到那些数据满足年龄和性别条件的标题。

由于这个问题,我有几个小时的头痛,我不再尝试了解决方案。希望有人能指出我正确的方向/解决方案。

非常感谢你。

1 个答案:

答案 0 :(得分: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')