Join two tables using Hibernate in Spring Boot Example

Join two tables using Hibernate in Spring Boot Example:

Many enterprise applications whichever using hibernate uses sql queries only for joins still and uses hibernate only for save/update operations. Today we are going to see how to use hibernate to join two tables. We are going to see how to get count(*) using hibernate along with group by function in hibernate projections.

How to create hibernate session from EntityManager?

Use @PersistenceContext annotation to get entityManager object. EntityManager can be used to get the hibernate session using getDelegate() method.

 

@Service
public class StoreServiceImpl implements StoreService {

@PersistenceContext
private EntityManager entityManager;

@Override
public List getAllStoresWithCount() {
// getting hibernate session
org.hibernate.Session session = (Session) entityManager.getDelegate();
}

}

 

Join two tables using JoinType:

 

org.hibernate.Session session = (Session) entityManager.getDelegate();
Criteria query = session.createCriteria(Store.class, "s"); // s is alias
query.createAlias("couponList", "c", JoinType.LEFT_OUTER_JOIN);

 

Here criteria is created with alias and join type as left outer join.

Store class:

@Entity
public class Store {
@OneToMany(mappedBy = "store")
private List couponList;

// I did not generate any getters/setters.
}

 

 

Coupon Class:

@Entity
public class Coupon {
@ManyToOne
private Store store;
public Store getStore() {
return store;
}

public void setStore(Store store) {
this.store = store;
}
}

 

 

Getting the count(*) with group by:

 

query.setProjection(Projections.projectionList()
.add(Projections.groupProperty("s.storeName"))
.add(Projections.rowCount()));

 

Selecting the required columns from the joins:

Add the required columns to projects property, it will return the result also the same order how you add.
All the strings like storeName, storeDesc inside property method should match with your store entity fields. (it is not column name).

query.setProjection(Projections.projectionList().add(Projections.property("s.storeId"))
.add(Projections.property("s.storeName")).add(Projections.property("s.storeDesc"))
.add(Projections.property("s.storeUrl")).add(Projections.property("s.storeAffUrl"))
.add(Projections.property("s.storeIsFeatured")).add(Projections.property("s.storeIsActive"))
.add(Projections.property("s.storeSlug")).add(Projections.property("s.storeLogo"))
.add(Projections.groupProperty("s.storeName"))
.add(Projections.rowCount()));

 

Executing and getting the result list:

List stores = query.list();
for (int i = 0; i < stores.size(); i++) {
Object[] storeObj = (Object[]) stores.get(i);
System.out.println(storeObj[0]);
}

 

Please let me know if you have any questions in the below comments section.

293 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *