jpa

cvxl0en2  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(242)

为了让我的问题简单明了,假设我有:

create table car (
    id int primary key auto_increment
);

create table part_meta (
    id int primary key auto_increment,
    `key` varchar(255),
    value varchar(255),
    car_id int,

    foreign key (car_id) references car(id)
)

现在假设我需要 car “包含”给定的 part-meta :

key=color
value=blue
and
key=year
value=2020

我将感谢您的帮助,如何实现这一点在querydsl
否则我会问不同的问题。我可以得到以下结果使用 JpaExpressions.selectOne()... :

select
    a.id
from
    car a
where
    (
        exists (
                select
                    1
                from
                    car_part m1
                where
                      m1.key='color'
                  and m1.value='blue'
            )
        )
  and (
    exists (
            select
                1
            from
                car_part m2
            where
                  m2.key='year'
              and m2.value='2020'
        )
    );

但我想把这两个子查询的范围缩小到 id 汽车的( and m1.id_car = a.id 以及 and m2.id_car = a.id ),拥有:

select
    a.id
from
    car a
where
    (
        exists (
                select
                    1
                from
                    car_part m1
                where
                        m1.key='color'
                  and m1.value='blue'
                  and m1.id_car = a.id
            )
        )
  and (
    exists (
            select
                1
            from
                car_part m2
            where
                    m2.key='year'
              and m2.value='2020'
              and m2.id_car = a.id
        )
    );

对未来的读者来说,我想我明白了:

ExpressionUtils.allOf(inputData.stream().map(e -> JPAExpressions
                    .selectOne()
                    .from(carMeta)
                    .where(carMeta.key.eq(e.getKey()),
                            carMeta.value.eq(e.getValue()),
                            carMeta.car.id.eq(car.id)
                    )
                    .exists()).collect(toSet()));

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题