【发布时间】:2020-08-18 15:01:47
【问题描述】:
我在 Spring Boot、Spring Data JPA 项目中使用 QueryDSL。
我有一个名为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,其中键是“测试”,值是“你好”和“世界”。
我还没有找到在 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 左右,具体取决于我要搜索的键/值对的数量。
有谁知道如何用 QueryDSL 做这样的事情?
编辑:
现在假设以下架构,有两个表:test 和“用户”:
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 表映射到User 类中的keyValues 属性?
【问题讨论】:
标签: java spring-boot spring-data-jpa querydsl