java - 如何使用 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
);
解决方案
如果没有 JPA 中的缩放器对象,您的要求是不可能的。即 JPA 不能给你一个
Product
只p.getUserProducts()
包含一些UserProducts
.您必须使用本机查询选项或任何其他选项来检索列并提供有关如何创建对象的映射器。您可以使用以下 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
推荐阅读
- swift - SwiftUI 中的 ORSSerialPort.send 无法连接
- php - 使用 mpdf 创建的可填写 PDF 未显示复选框
- javascript - 输入解析提取响应的意外结束
- flutter - 使用颤振文档在每个视图图块上创建带有心形图标的随机单词列表视图。(请在下面找到问题)
- bash - 将日期格式化为 Bash 中的特定时间间隔
- c# - 有没有办法抽象一个作为参数发送到类中的字段的函数?
- ios - 使用自动单元格高度隐藏 UITableView 的单元格子视图的正确方法是什么
- airflow - 气流 - 一次性跳过所有下游任务
- node.js - 当我运行这个脚本时,谁能指导我发生了什么?我错过了什么,我该如何解决?
- python - 如何使用 python 将更大的文件(60mb+)上传到 blob 存储?