Я использую createCriteria с uniqueResult, чтобы выбрать объект по id следующим образом:
1- Услуга:
@Service
@Transactional
public class MyService {
public Employee getEmployeeById(long employeeId) {
return employeeDao.getEmployeeById(employeeId);
}
}
2- DAO:
@Repository
public class EmployeeDaoImpl extends AbstractDao implements EmployeeDao {
public Employee getEmployeeById(long employeeId) {
return (Employee) super.getById(Employee.class, employeeId);
}
}
3- AbstractDao:
@Repository
public class AbstractDao {
@Autowired
private SessionFactory sessionFactory;
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public Object getById(Class clazz, long idValue) {
return getCurrentSession().createCriteria(clazz)
.add(Restrictions.idEq(idValue)).uniqueResult();
}
}
4- Сущность:
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "employee_id", unique = true, nullable = false)
@Basic(fetch = FetchType.EAGER)
private long id;
@Column(name = "first_name", length = 100, nullable = false)
private String firstName;
@Column(name = "last_name", length = 100, nullable = false)
private String lastName;
@Column(name = "email", length = 155, nullable = false)
private String email;
@Column(name = "password", nullable = false)
private String password;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "fk_department_id", nullable = true)
private Department department;
@ManyToMany(fetch = FetchType.LAZY)
@Fetch(FetchMode.SELECT)
@JoinTable(name = "employee_role", joinColumns = { @JoinColumn(name = "employee_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
private Set<Role> roles = new HashSet<Role>(0);
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.employee")
@Cascade(value = { CascadeType.ALL })
@Fetch(FetchMode.SELECT)
private Set<EmployeeGroup> employeeGroups = new HashSet<EmployeeGroup>(0);
}
ПРОБЛЕМА: при вызове метода службы, который получает сотрудника по id, показывая SQL, я заметил, что запрос на выбор сотрудника выполняется 3 раза следующим образом:
Hibernate:
select
this_.employee_id as employee1_2_0_,
this_.fk_department_id as fk13_2_0_,
this_.email as email2_0_,
this_.first_name as first5_2_0_,
this_.last_name as last8_2_0_,
this_.password as password2_0_
from
employee this_
where
this_.employee_id = ?
Hibernate:
select
this_.employee_id as employee1_2_0_,
this_.fk_department_id as fk13_2_0_,
this_.email as email2_0_,
this_.first_name as first5_2_0_,
this_.last_name as last8_2_0_,
this_.password as password2_0_
from
employee this_
where
this_.employee_id = ?
Hibernate:
select
this_.employee_id as employee1_2_0_,
this_.fk_department_id as fk13_2_0_,
this_.email as email2_0_,
this_.first_name as first5_2_0_,
this_.last_name as last8_2_0_,
this_.password as password2_0_
from
employee this_
where
this_.employee_id = ?
есть идеи, почему у меня такое поведение и как его настроить?