首页 > 解决方案 > 如何使用 HQL 选择带有额外表的休眠中的所有行

问题描述

更新 2

询问:

select distinct p.name, u.cookie_id
    from product p
    left join user_product up on p.id = up.product_id
    left join user u on up.user_id = u.id
    where p.active = true
    and
    (
       u.cookie_id = '4c2fe5b2-73fe-4b28-baa6-23db0512114c'
           or
       not (exists (
         select p1.id
         from user_product up1, product p1
         where p1.id = up1.product_id
       ))
    )

输出: 在此处输入图像描述

应该如何: 在此处输入图像描述

更新 1

stream()为了更好地理解问题,我编写了代码:

        List<Product> productList = productRepository.findAllByActiveTrue();
        productList = productList.stream().map(item -> {
            if(item.getUserProducts() == null) return item;

            List<UserProduct> userProductList = new ArrayList<>();
            for (UserProduct userProduct : item.getUserProducts()) {
                if(userProduct.getUser().getCookieId().equals(cookieId)){
                    userProductList.add(userProduct);
                }
            }
            item.setUserProducts(userProductList);
            return item;
        }).collect(Collectors.toList());

我想知道如何正确地从表中选择数据。我想获得所有产品。

但是要获得所有产品很容易。如果产品和用户之间通过 CookieId 建立连接,我还需要包含在输出数据(用户产品和用户)中。换句话说,如果用户的 cookieId 与查询中的 cookieId 不匹配,我想显示所有具有 User 和 UserProducts 的产品(如果可能)并排除关系 Product-UserProduct-User 。

我正在尝试以下查询,但它只返回用户与产品之间有联系的产品,而不是所有产品。

@Query("from Product pr join fetch pr.userProducts up left join fetch up.user u where pr.active = true and u.cookieId = :cookieId")
    List<Product> getAllProductsByCookieId(UUID cookieId);

我的数据库如下所示: 数据库

想法的可视化: 在此处输入图像描述

用于生成表的 SQL 查询:

产品表

create table if not exists product
(
    id bigint auto_increment
        primary key,
    active bit not null,
    image_path varchar(255) null,
    name varchar(255) null,
    price double not null,
    unit_number double null,
    unit_type varchar(255) null
);

用户产品表

create table if not exists user_product
(
    quantity int null,
    product_id bigint not null,
    user_id bigint not null,
    primary key (product_id, user_id),
    constraint FKnw43wab2rt35jmofmpbhkibco
        foreign key (product_id) references product (id),
    constraint FKq5o2e33vlwpfc2k1mredtia6p
        foreign key (user_id) references user (id)
);

用户表

create table if not exists user
(
    id bigint auto_increment
        primary key,
    cookie_id varchar(255) null
);

标签: javahibernatespring-data-jpahqljpql

解决方案


  1. 如果没有 JPA 中的缩放器对象,您的要求是不可能的。即 JPA 不能给你一个Productp.getUserProducts()包含一些UserProducts.

  2. 您必须使用本机查询选项或任何其他选项来检索列并提供有关如何创建对象的映射器。您可以使用以下 sql 查询。

    select p.product, u.cookie_id 
    from product p 
    left join user_product up on p.id = up.product_id 
    left join user u on up.user_id = u.id and u.cookie_id = '?1'
    where p.active = true
    group by p.product, u.cookie_id

推荐阅读