如何使用hibernate连接两个表

时间:2016-08-20 09:54:25

标签: java mysql hibernate

我想使用HQL或Criterial

连接两个表

表是

  • 购物车表(cartId,bookid,customeremailid,quantity)
  • 书桌(bookId,bookName,bookPrice,bookQuantity)

我的SQL查询是这样的

select count(c.cartId) as cartId,b.bookName as bookName,c.customeremailid as customeremailid,sum(b.bookPrice)as c.price,c.quantity from Book b,Cart c where  c.customeremailid='"+customeremailid+"' and b.bookId=c.bookid

将计算cartIdbookPrice

的总和

我将此结果存储到List<Cart>

以下是cart POJO变量

private int bookid,cartId;
    private String customeremailid,bookName,bookDescription,image;
    private int quantity;
    private long price;

HQL查询:

String sql="select count(c.cartId) as cartId,b.bookName as bookName,c.customeremailid as customeremailid,sum(b.bookPrice)as price,c.quantity from Book b,Cart c where  c.customeremailid='"+customeremailid+"' and b.bookId=c.bookid";
             Query q=s.createSQLQuery(sql);
             Cartlist=q.setResultTransformer(Transformers.aliasToBean(Cart.class)).list();


             for(Cart c :Cartlist)
             {
                 System.out.println("in cart : "+c.getCartId());
                 System.out.println("in cart : "+c.getPrice());
             }

我没有在Hibernate中做到这一点

好的建议 感谢

1 个答案:

答案 0 :(得分:0)

使用下面的hibernate Criteria示例代码加入:

List cats = sess.createCriteria(Cat.class)
    .createAlias("kittens", "kt")
    .createAlias("mate", "mt")
    .add( Restrictions.eqProperty("kt.name", "mt.name") )
    .list();

参考:https://docs.jboss.org/hibernate/orm/3.5/reference/en/html/querycriteria.html#querycriteria-associations