【问题标题】:Hibernate Criteria Example休眠条件示例
【发布时间】:2011-11-15 05:46:24
【问题描述】:

我有表 'Stores' 和 'Item' 。项目表有列 'Category' 、 'Brand' 、 'itemcode'。 此外,我将类别详细信息和品牌详细信息保存在另外 2 个名为 Category 和 Brands 的表中。 Stores 表具有称为 item 和 qty 的 locums。我的休眠实体类是 Stores、Item、Category、Brand。
我想通过休眠从商店获取给定商品的商品。为商品设置类别和品牌名称是根据用户的偏好完成的。(这意味着,用户从摇摆用户界面中选择类别和品牌,然后应用程序必须设置具有给定类别和品牌名称的项目。)应根据商店中的给定项目选择项目。我是怎么做的:

 Stores stores = new Stores();  

 Item item = new Item();  
 if (isBrandNameMode()) {  //here checks if user select a brand in IF clause
     item.setBrands(selectedBrand);  
     //selectedBrand is an brand object which user selected  
 }  

 if (isCategoryode()) {// here checks if user select a category in IF clause
     item.setSizeModel(selectedSize);  
     //user selected 
 }   

 Criteria cr=HSession.getSession().createCriteria(Stores.class);  
 cr.add(Restrictions.eq("item", item));  
 List l=cr.list();  
 System.out.println("list size is: "+l.size());

但是这里所有商店的物品都被退回,但不是给定的物品。
我也试过Critataria Example

stores.setItem(item);
cr.add(Example.create(stores))
但已退回商店中的所有商品。如何根据给定物品从商店获取物品。

【问题讨论】:

    标签: java hibernate swing desktop-application criteria


    【解决方案1】:

    您是否在 Item 类中定义了 equals/hashcode?​​p>

    【讨论】:

    • 是的,对于 item 类,equal 方法被覆盖了。
    • Stores和Item是什么关系?为什么用复数形式调用您的对象 Stores 而不是 Store
    • equals/hashcode 是如何定义的?你碰巧使用了 id 字段吗?
    • 存储表有商品数量。 equa 方法已被项目的 ID 覆盖。
    • id不能放在equals方法中(尤其是hibernate自动生成的),真的应该选择另外一个业务key。请看这里的解释:community.jboss.org/wiki/EqualsAndHashCode
    【解决方案2】:
                   Criteria crt=session.createCriteria(Product.class);            
                List<Product> l=crt.list();
                for(Product p:l)
                {
                    System.out.println(p.getPrice());
                    System.out.println(p.getProductId());
                    System.out.println(p.getProName()); 
                }
    

    【讨论】:

    • 请发布更多的代码答案,它应该有一些文字支持。
    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2011-06-06
    • 2016-10-04
    • 2012-08-26
    相关资源
    最近更新 更多