how to join two tables using hibernate

java mysql hibernate

729 просмотра

1 ответ

I want to join two tables using HQL or Criterial

Tables are

  • Cart table(cartId,bookid,customeremailid,quantity)
  • Book table(bookId,bookName,bookPrice,bookQuantity)

My sql query is like this

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

which will give the count of cartId and sum of bookPrice

i am storing this result into List<Cart>

following is cart POJO variables

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

HQL Query :

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());
             }

Iam not getting how to do it in Hibernate

kindly suggest Thanks

Автор: Gajula Vijay Источник Размещён: 08.11.2019 11:08

Ответы (1)


0 плюса

Joins using hibernate Criteria example code below:

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

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

Автор: Sumit Badaya Размещён: 20.08.2016 10:58
Вопросы из категории :
32x32