Friday, 21 December 2018

Hibernate Interview Questions


    1. filter employees with same salary count greater than five (group by salary) using hibernate criteria?
      1. Session session = getCurrentSession(); ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.groupProperty("totalCode")) .add(Projections.groupProperty("activityCode")) .add(Projections.sum("amount")) .add(Projections.rowCount()); Criteria criteria = session.createCriteria(Payment.class); criteria.setProjection(projectionList); List payments = criteria.list(); for (Object[] payment : payments) { System.out.println("totalCode: " + payment[0]); System.out.println("activityCode: " + payment[1]); System.out.println("amountSum: " + payment[2]); System.out.println("rowCount: " + payment[3]); }
    2. What is Hibernate N+1 Problems and its Solution?
      1. Hibernate n+1 problems only comes for one to many relationship.
      2. Let us see this problem by example – We have Department table with a one-to-many relationship with Employee. One Department may have many Employees.
      3. We have written the Hibernate Department Entity as below.
      4. @Entity public class Department { private Long id; @OneToMany private Employee[] Employees; }
      5. So now you want to print out all the details of Employee models. A native O/R implementation would SELECT all Department and then do N additional SELECTs for getting the information of Employee for each department.
      6. -- To Get all Departments SELECT * FROM Department; -- To get each Employee, get Employee details SELECT * FROM Employee WHERE Employee.departmentId = ?
      7. As you see, the N+1 problem can happen if the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.
      8. Solution for Hibernate N+1 Problem
        1. Using HQL fetch join
          1. You can use the fetch while using the HQL as below example.
          1. from Department d join fetch d.employees Employee
          2. Hibernate Generated SQL would be similer as –
          3. SELECT * FROM Department d LEFT OUTER JOIN Employee e ON d.id = d.department_id
        1. Using Criteria query
          1. Criteria criteria = session.createCriteria(Department.class); criteria.setFetchMode("employees", FetchMode.EAGER);
        2. In both above cases, the query returns a list of Department objects with the Employee initialized, and only one query needs to be run to return all the Department and Employee information required.

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *