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.


public class StoreServiceImpl implements StoreService {

private EntityManager entityManager;

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:

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

// I did not generate any getters/setters.



Coupon Class:

public class Coupon {
private Store store;
public Store getStore() {
return store;

public void setStore(Store store) { = store;



Getting the count(*) with group by:




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).



Executing and getting the result list:

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


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

1,020 total views, 2 views today

Leave a Reply

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