【问题标题】:Hibernate: Get a list of top level categories from Store itemsHibernate:从 Store 项目中获取顶级类别的列表
【发布时间】:2013-03-17 08:42:08
【问题描述】:

我的 Hibernate 应用程序中有以下实体:-

Store, Item, Category与以下关系

StoreItem 具有一对多关系

Category 与其他类别具有多对多关系(即父类别具有子类别)

Item 与具有相同父类别的类别具有多对多关系。

我想要一个商店拥有其商品的顶级类别的列表。

我尝试了这个 HQL 查询,但它只返回一个顶级类别

String queryString = "select c.parentCategory from Category c where :store in elements(c.items)";

列出类别 = getSession().createQuery(queryString).setEntity("store", store).list();

请帮我解决这个问题。

提前致谢。

【问题讨论】:

    标签: java database hibernate hql


    【解决方案1】:

    您可以在逻辑级别和 ORM 级别实现它,而不仅仅是在 ORM 级别。

    首先添加关系:store与Category是一对多的关系 其次,在插入/更新/删除项目之前添加一个预处理器,用于在商店级别添加或删除类别。

    public void preProcessForItemInserting(Item item){
        Store store = getStoreDao().get( item.getStoreId() );
        Set<Category> storeCategories = store.getCategories();
        Set<Category> itemCategories = item.getCategories();
        storeCategories.addAll( itemCategories );
        getStoreDao().save( store );
    }
    
    //it is a little bit more complex than inserting logic
    public void preProcessForItemUpdating(Item item){...}
    
    //it is a little bit more complex than inserting logic
    public void preProcessForItemDeleting(Item item){...}
    

    总而言之,这是面向数据设计和面向应用设计的经典问题。我们可以根据需求在这两个方面调整我们的应用程序,而不仅仅是数据建模或应用程序优化。

    【讨论】:

      【解决方案2】:

      我以前做过类似的事情,但稍微简化了一点。如果一个类别只能有一个父类别,您可以将其建模为:

      @Entity
      public class Category
      
      @OneToMany(mappedBy = "parentCategory", cascade = CascadeType.ALL, orphanRemoval = true)
      private List<Category> childCategories;
      
      @ManyToOne
      @JoinColumn(name = "parentCategoryId", nullable = true)
      private Category parent;
      

      查找顶级类别是查找父级为空的类别的简单案例。

      sessionFactory.getCurrentSession().createQuery("from Category where parent is NULL")
      

      这符合我的需要,但需要限制类别只能有一个父项。

      【讨论】:

      • 感谢@Alex,但我的问题更进一步。我希望列表仅包含商店商品的顶级类别,也就是说,返回的父类别应该每个都至少有一个包含特定商店商品的子类别。你有什么解决办法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多