gpt4 book ai didi

java - 创建通过检查相关列表中的项目来选择的查询

转载 作者:行者123 更新时间:2023-12-01 18:44:30 24 4
gpt4 key购买 nike

我有 Shop 实体:

@Entity
@Table(name = "shop")
public class Shop {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="shop_id")
private List<OpenDay> openDays = new ArrayList<>();
}

OpenDay实体:

@Entity
@Table(name = "open_day")
public class OpenDay {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private LocalDate date;
}

我需要一个查询来选择所有具有 OpenDaydate 设置为特定日期的 Shop,比如说今天和明天,我选择今天和明天营业的商店。我怎样才能实现这个目标?Criteria API 是首选,因此我将能够将它与 spring-data-jpa Specification 一起使用。谢谢。

最佳答案

据我了解 open_day 表包含 shop_id 列。因此,我建议您将 Shop 字段添加到 OpenDay 实体。

@Entity
@Table(name = "open_day")
public class OpenDay {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private LocalDate date;

@ManyToOne
@JoinColumn(name="shop_id")
private Shop shop;
}

然后

EntityManager entityManager;

public List<Shop> getShopsByOpenDates(List<LocalDate> dates) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Shop> query = builder.createQuery(Shop.class);
Root<OpenDay> openDay = query.from(OpenDay.class);

Predicate predicate = openDay.get("date").in(dates);

query.select(openDay.get("shop")).distinct(true).where(predicate);

return entityManager.createQuery(query).getResultList();
}

关于java - 创建通过检查相关列表中的项目来选择的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com