【问题标题】:Create query which selects by checking items in related list创建通过检查相关列表中的项目进行选择的查询
【发布时间】:2020-05-09 02:03:30
【问题描述】:

我有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 一起使用。谢谢。

【问题讨论】:

    标签: java jpa spring-data-jpa criteria criteria-api


    【解决方案1】:

    据我了解open_day 表包含shop_id 列。所以我建议你在OpenDay实体中添加Shop字段。

    @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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多