如何在Hibernate中创建条件查询?

时间:2016-05-04 07:20:48

标签: java spring hibernate jpql

我是Hibernate的新手,我想在学习Hibernate中的CriteriaQuery时将JPQL转换为Criteria Query。我成功地能够创建JPQL但在条件中得到了Stopped。以下是我的情景:

项目类别:

    @Entity
    @Table(name = "ITEM")
     public class Item   {

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

        @Version
        @Column(name = "OBJ_VERSION")
        private int version = 0;

        @Column(name = "ITEM_NAME", length = 255, nullable = false, updatable = false)
        private String name;

        @ManyToOne(fetch=FetchType.EAGER,  cascade = CascadeType.ALL) 
        @JoinColumn(name="itemSellerId") 
         private User seller;

        @Transient
        private User buyer;
........

用户类::

...
 @OneToMany(fetch=FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
        private Set<Item> boughtItems = new HashSet<Item>();
..

我的JPQL查询正常运行::

public List<Item> findBySellerOrBuyer(Long sellerId,Long buyerId) {
        Query query = entityManager.createQuery("select distinct i from Item i, User u  "
                + "where (i.initialPrice >  22 and i.seller.id = :sellerId) "
                +                   "OR "
                + "( u.id = :buyerId and i member of u.boughtItems and  i.initialPrice = i.reservePrice  )");
        return (List<Item>) query.setParameter("sellerId", sellerId).setParameter("buyerId", buyerId).getResultList();

    }

条件是:: 条件查询获取匹配的项: a)卖方&amp;初始价格&gt; 22.0 要么 b)买方&amp;保留价格=初始价格

谢谢:)

上次更新

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Item> cr = builder.createQuery(Item.class);

        Criterion price = Restrictions.gt("initial price", 22);
        Criterion name = Restrictions.eq("seller.id","abc");

        Criterion Buyer = Restrictions.eq("buyer.id","abc");
        Criterion reserved_price = Restrictions.eq("reserved_price","initial_price");

        // To get records matching with AND condition for price  & name 
        LogicalExpression andExp = Restrictions.and(name, price);
        LogicalExpression andExp2 = Restrictions.and(Buyer, reserved_price);




        return (List<Item>) ((Criteria) cr).list();

1 个答案:

答案 0 :(得分:0)

使用以下代码 -

Criteria cr = session.createCriteria(Item.class);

Criterion price = Restrictions.gt("initial price", 22);
Criterion name = Restrictions.eq("seller.id","abc");

Criterion Buyer = Restrictions.eq("buyer.id","abc");
Criterion reserved_price = Restrictions.eq("reserved_price","initial_price");

 Disjunction objDisjunction = Restrictions.disjunction();
            /* Add multiple condition separated by OR clause within brackets. */
objDisjunction.add(Restrictions.and(price , name ));
objDisjunction.add(Restrictions.and(Buyer, reserved_price));
cr.add(objDisjunction);
List results = cr.list();