我对JPA中的过滤条件有疑问,是否可以仅针对过滤条件调用另一个Entity类
我在EmployeeDAOImp
中有一个名为findEmployee
的方法,当加载JSF页面时,该方法将在ManagedBeans中调用。当用户在JSF的数据表中放入过滤条件时,它会搜索相应的实体类Employee
(Employee_
元模型)
我想知道是否可以将另一个名为EmployeeAll_
的实体类仅用于过滤,即当用户应用过滤器而不是Employee_
类时?
Employee_
和EmployeeAll_
类之间的差异是第一个没有所有员工记录(仅限于他的部门,后者有所有员工(所有部门)。两者都返回相同的一组列fom数据库。
任何帮助都非常值得赞赏。
EmployeeDAOImpl class
public void findEmployee(Employee employee) {
try {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> e = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
e.orderBy(cb.desc(emp.get("employeeNo")));
c.select(emp);
CriteriaQuery<Long> countQ = cb.createQuery(Long.class);
Root<Employee> empCount = countQ.from(Employee.class);
countQ.select(cb.count(empCount));
String employeeNo = employee.getEmployeeNo("");
List<Predicate> criteria = new ArrayList<Predicate>();
if (employeeNo != null) {
ParameterExpression<String> pexp =
cb.parameter(String.class,"employeeNo");
Predicate predicate =
cb.like(emp.get(Employee_.employeeNo),pexp);
criteria.add(predicate);
}
TypedQuery<Employee> q = entityManager.createQuery(c);
if (employeeNo != null) {
q.setParameter("employeeNo", employeeNo+"%");
}
答案 0 :(得分:1)
避免将all_employees_view
映射为实体,因为它显示与Employee基本相同的对象类型。
将登录的员工信息存储在会话范围的bean中,通过ManagedProperty注释注入bean,将其传递给负责构建查询的dao服务,最后,是的,在查询条件中使用它。 / p>
<强>系强>
@Entity
public class Department {
@Id
private Integer id;
@OneToMany(mappedBy="department")
private Collection<Employee> employees;
}
<强>员工强>
@Entity
public class Employee {
@Id
private Integer id;
@ManyToOne
@JoinColumn(name="department_id")
private Department department;
}
<强>的UserBean 强>
@ManagedBean
@SessionScoped
public class UserBean {
private Employee user; // + getter, setter. The property is set during login
}
<强>引用EmployeeBean 强>
@ManagedBean
@ViewScoped
public class EmployeeBean {
@ManagedProperty(value="#{userBean}")
private UserBean userBean; // + setter
// this bean retrieves the records pertaining the logged-in user's department:
Department userDepartment;
@PostConstruct
private void init() {
userDepartment = userBean.getUser().getDepartment();
}
}
最后,让您的DAO服务实现一个以userDepartment
作为输入参数的find方法。