簡體   English   中英

HQL 查詢以選擇按與已建立實體相關的參數值分組的所有唯一實體

[英]HQL query to select all unique entities grouped by the parameter value that is in relation to founded entities

所以,我被下一個任務困住了。 假設我有餐廳。 它可以有很多訂單,其中一些訂單可能具有相同的 IngredientType 但具有不同的到期時間。 我需要編寫 HQL,通過給定的 restaurantId 和 IngredientTypes 列表將獲得最新鮮的結果(通過 IngredientInfo 實體中的 expiresAt 字段)。

假設我們有餐廳 = 1; IngedientTypes 列表:POTATO、SALMON。 餐廳有 2 個訂單:

1: { {POTATO: {expiresAt: 4}, {ORANGE:{expiresAt: 11} } 
2: { {POTATO: {expiresAt: 9}, {SALMON: {expiresAt: 6} }

. 返回結果:

[{POTATO: {expiresAt: 4}, {SALMON: {expiresAt: 6}]

我有 4 個實體:

@Entity
        @Table(name = "restaurants")
        public class RestaurantEntity {
        
            @Id
            @GeneratedValue(strategy =  GenerationType.IDENTITY)
            Long id;
        
        }

    


@Entity
    @Table(name = "orders")
    public class OrderEntity {

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

      @ManyToOne(fetch = FetchType.EAGER)
      @JoinColumn(name = "restaurantId")
      RestaurantEntity restaurant;

      @OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
      @BatchSize(size = 10)
      List<IngredientEntity> ingredients;

  }

    @Entity
    @Table(name = "ingredients")
    public class IngredientEntity {

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

    @Enumerated(EnumType.STRING)
    private IngredientType ingredientType;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "orderId")
    private OrderEntity order;

    @OneToMany(mappedBy = "ingredient", cascade = CascadeType.ALL)
    @BatchSize(size = 10)
    private List<IngredientInfoEntity> ingredientInfos
}


@Entity
@Table(name = "ingredient_info")
public class IngredientInfoEntity {

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

    @ToString.Exclude
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ingredientId")
    IngredientEntity ingredient;

    Instant expriresAt;
}

我確實寫了一些查詢:

@Query(value = " SELECT ie " +
                " FROM OrderEntity oe INNER JOIN IngredientEntity ie " +
                " ON oe.id = ie.order " +
                " WHERE oe.restaurant.id = :restId AND ie.ingredientType in (:ingredientTypes) ")
List<IngredientEntity> findIngredients(String restId, List<IngredientType> ingredientTypes);

它確實讓我返回: [{POTATO: {expiresAt: 9}, {POTATO: {expiresAt: 4}, {SALMON: {expiresAt: 6}]

所以,基本上我可以以編程方式過濾該列表,但我的問題是是否可以編寫 HQL 來做到這一點?

是的,可以使用 HQL(休眠查詢語言)過濾實體項。

Hibernate 在其 HQL 查詢中支持命名參數。 這使得編寫接受用戶輸入的 HQL 查詢變得容易,並且您不必防御 SQL 注入攻擊。 以下是使用命名參數的簡單語法 -

String hql = "FROM Employee E WHERE E.id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();

您可以在此處探索有關 HQL 的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM