id 我有以下模式的表,名为 test
:
| id | key | value |
|----|------|-------|
| 1 | test | hello |
| 1 | test | world |
| 2 | test | hello |
| 2 | foo | bar |
| 3 | test | hello |
| 3 | test | world |
现在我想在QueryDSL中写以下SQL。
select id from test where key = 'test' and value = 'hello'
INTERSECT
select id from test where key = 'test' and value = 'world'
这将给我所有的id,其中键是 "test",值是 "hello "和 "world"。
我还没有找到在QueryDSL中声明这种SQL的方法。我可以写出两个select语句,但是我在将它们与一个 INTERSECT
.
JPAQueryFactory queryFactory = new JPAQueryFactory(em); // em is an EntityManager
QTestEntity qTestEntity = QTestEntity.testEntity;
var q1 = queryFactory.query().from(qTestEntity).select(qTestEntity.id).where(qTestEntity.key("test").and(qTestEntity.value.eq("hello")));
var q2 = queryFactory.query().from(qTestEntity).select(qTestEntity.id).where(qTestEntity.key("test").and(qTestEntity.value.eq("world")));;
最后,我想检索一个符合给定查询的id列表。一般来说,相交的数量在20或30个左右,这取决于我想搜索的key-value-pair的数量。
有谁知道如何用QueryDSL做这样的事情?
EDIT:
假设现在的模式如下,有两个表。test
和'user':
test:
| userId | key | value |
|---------|------|-------|
| 1 | test | hello |
| 1 | test | world |
| 2 | test | hello |
| 2 | foo | bar |
| 3 | test | hello |
| 3 | test | world |
user:
| id | name |
|----|----------|
| 1 | John |
| 2 | Anna |
| 3 | Felicita |
对应的java类是这样的: TestEntity
有一个包含所有属性的复合键。
@Entity
public class TestEntity {
@Id
@Column(name = "userId", nullable = false)
private String pubmedId;
@Id
@Column(name = "value", nullable = false)
private String value;
@Id
@Column(name = "key", nullable = false)
private String key;
}
@Entity
class User {
@Id
private int id;
private String name;
@ElementCollection
private Set<TestEntity> keyValues;
}
我怎样才能映射出 test
表到 keyValues
内的属性 User
类?