- filter employees with same salary count greater than five (group by salary) using hibernate criteria?
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
- What is Hibernate N+1 Problems and its Solution?
- Hibernate n+1 problems only comes for one to many relationship.
- 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.
- We have written the Hibernate Department Entity as below.
@Entity public class Department { private Long id; @OneToMany private Employee[] Employees; }
- 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.
- -- To Get all Departments SELECT * FROM Department; -- To get each Employee, get Employee details SELECT * FROM Employee WHERE Employee.departmentId = ?
- 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.
- Solution for Hibernate N+1 Problem
- Using HQL fetch join
- You can use the fetch while using the HQL as below example.
from Department d join fetch d.employees Employee
- Hibernate Generated SQL would be similer as –
SELECT * FROM Department d LEFT OUTER JOIN Employee e ON d.id = d.department_id
- Using Criteria query
Criteria criteria = session.createCriteria(Department.class); criteria.setFetchMode("employees", FetchMode.EAGER);
- 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.
Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts
Friday, 21 December 2018
Hibernate Interview Questions
Wednesday, 5 December 2018
Hibernate one to one mapping
- In this kind of association, a foreign key column is created in owner entity. For example, if we make EmployeeEntity owner, then a extra column "ACCOUNT_ID" will be created in Employee table. This column will store the foreign key for Account table.
- To make such association, refer the Account entity in EmployeeEntity class as follow:
@OneToOne @JoinColumn(name="ACCOUNT_ID") private AccountEntity account;
- @JoinColumn
- The join column is declared with the @JoinColumn annotation which looks like the @Column annotation, It is used in column owner column and mapped by used in other table. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join.
- mappedBy
- mappedBy is used. ‘mappedBy’ refers to the property name of the association on the owner side.AccountEntity.java
-
@OneToOne(mappedBy="account") private EmployeeEntity employee;
Hibernate Many-To-One Bidirectional
- One table has a foreign key column that references the primary key of associated table.In Bidirectional relationship, both side navigation is possible.
- We are discussing an example of Student and University relationship. Many student can enroll at one University. And one University can have many students.
@Entity @Table(name = "STUDENT") public class Student { @Id @GeneratedValue @Column(name = "STUDENT_ID") private long id; @Column(name = "FIRST_NAME") private String firstName; @ManyToOne(optional = false) @JoinColumn(name = "UNIVERSITY_ID") private University university; ------------------------ ------------------------ } @Entity @Table(name = "UNIVERSITY") public class University { @Id @GeneratedValue @Column(name = "UNIVERSITY_ID") private long id; @Column(name = "NAME") private String name; @Column(name = "COUNTRY") private String country; @OneToMany(mappedBy = "university", cascade = CascadeType.ALL) private List
students; } - @JoinColumn says that Student table will contain a separate column UNIVERSITY_ID which will eventually act as a foreign key reference to primary key of University table
Many to Many Annotation
- In this scenario, any given employee can be assigned to multiple projects and a project may have multiple employees working for it, leading to a many-to-many association between the two.
- We have an employee table with employee_id as its primary key and a project table with project_id as its primary key. A join table employee_project is required here to connect both sides.
- The model classes Employee and Project need to be created with JPA annotations:
@Entity @Table(name = "Employee") public class Employee { // ... @ManyToMany(cascade = { CascadeType.ALL }) @JoinTable( name = "Employee_Project", joinColumns = { @JoinColumn(name = "employee_id") }, inverseJoinColumns = { @JoinColumn(name = "project_id") } ) Set
projects = new HashSet<>(); // standard constructor/getters/setters } @Entity @Table(name = "Project") public class Project { // ... @ManyToMany(mappedBy = "projects") private Set employees = new HashSet<>(); // standard constructors/getters/setters } - Both the Employee class and Project classes refer to one another, which means that the association between them is bidirectional.
- In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations.
- @ManyToMany
- The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.
- @JoinTable
- In our example, the owning side is Employee so the join table is specified on the owning side by using the @JoinTable annotation in Employee class
- @JoinColumn
- The @JoinColumn annotation is used to specify the join/linking column with the main table. Here, the join column is employee_id and project_id is the inverse join column since Project is on the inverse side of the relationship
- mappedBy
- In the Project class, the mappedBy attribute is used in the @ManyToMany annotation to indicate that the employees collection is mapped by the projects collection of the owner side