tsk
tsk

Reputation: 1

Hibernate LAZY fetching issue

I have two classes Employee and Roles.Employee has many roles and each role has many Employees. So that I have used ManyToMany relationship by taking another table 'EMPLOYEE_ROLES'.

In Employee class:

@ManyToMany(fetch = FetchType.LAZY,cascade={CascadeType.ALL})
@JoinTable(name="EMPLOYEE_ROLES",joinColumns=     {@JoinColumn(name="EC",nullable=false,updatable=false)},inverseJoinColumns={@JoinColumn(name = "ROLE_ID", 
        nullable = false, updatable = false) }) 
public Set<Roles> getRolesList() {
    return rolesList;
}

and

In Roles class:

  @ManyToMany(fetch = FetchType.LAZY,cascade={CascadeType.ALL},mappedBy="rolesList")
public Set<Employee> getEmployees() {
    return employees;
}

But when I am fetching Employee And accessing roleList, roles are loaded perfectly but along with fetching delete query fired on EMPLOYEE_ROLES table.

 Employee ec=employeeService.findByEmployeeCode(121);
 Iterator<Roles> itr=ec.getRolesList().iterator();

Please can anyone suggest me. If I use fetchType.EAGER it works perfectly, but when I use LAZY,then only this problem comes:

 Hibernate: select roleslist0_.EC as EC11_1_, roleslist0_.ROLE_ID as ROLE2_41_1_, roles1_.ID as ID8_0_, roles1_.DESCRIPTION as DESCRIPT2_8_0_, roles1_.ROLES as ROLES8_0_ from EMPLOYEE_ROLES roleslist0_ inner join ENABLE.ROLES roles1_ on roleslist0_.ROLE_ID=roles1_.ID where roleslist0_.EC=?
 Hibernate: delete from EMPLOYEE_ROLES where EC=?

Upvotes: 0

Views: 406

Answers (2)

yayatip
yayatip

Reputation: 79

You have cascade={CascadeType.ALL} on both the sides, try removing cascade on the role side.

Upvotes: 0

M&#225;rio Kapusta
M&#225;rio Kapusta

Reputation: 508

Add @Transactional annotation on method where you call getters from LAZY fetch type. For example:

@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void doSomething(){
  ...
  Iterator<Roles> itr=ec.getRolesList().iterator();
  ...
}

Upvotes: 1

Related Questions