How to handle join query in Hibernate and Spring with annotations? How to handle join query in Hibernate and Spring with annotations? spring spring

How to handle join query in Hibernate and Spring with annotations?


There is an association between EmployeeInfoForm and EmployeeLoginForm that I am not seeing in your code. Maybe there is an Employee class there? If that is the case then you need to add that. So let us assume that each employee has many forms. Then you will code the Employee side of the relationship like this:

 public class Employee{      @OneToMany(cascade = CascadeType.ALL, mappedBy = "employee")      private Set<EmployeeLoginForm> loginForms = new HashSet<EmployeeLoginForm>();      ... }

And the Many side of the relationship in the EmployeeLoginForm class:

 @ManyToOne Employee employee;

This will create the table structure such that:

 emploee = (id, etc ...) employeelogin = (id, employee, ....)

Now, any time you need a list of the Logins of an Employee you get it from the Employee object without needing a Query.

 Set<EmployeeLoginForm> logins = e.getLoginForms(); //where e is an employee object.

If you did want to query you can do

 select o from EmployeeLoginForm o join o.employee

But that is unnecessary in this case.


You are thinking in database / pure SQL terms when you talk about performing joins with select statements. The power (and danger) of Hibernate is that it abstracts this away from you and lets you think in Object terms. What you need is a relationship between the 2 objects and then let Hibernate handle this relationship.

I recommend you spend some time reading this:

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html

to get a better understanding of how Hibernate can help.


You can do the following using the Hibernate criteria projection:

public List extractEmployeeAttributes() {    log.debug("extractEmployeeAttributes");    try {                    Session session = sessionFactory.getCurrentSession();                    session.beginTransaction();           Criteria c1 = session.createCriteria(employee_info.class,emp_info);           Criteria c2 = session.createCriteria(employee_login.class,emp_log);           c1.setProjection(Projections.projectionList()                                .add(Projections.property("empid"))                                .add(Projections.property("empname"))                                .add(Projections.property("jobtitle"))                                .add(Projections.property("employee_info "))                                .add(Restrictions.and(Property.eqName(emp_info.empId,emp_log.empId))          return c1.list();    } catch (RuntimeException re) {        log.error("extractEmployeeAttributes failed", re);        throw re;    }}