如何使用 CriteriaBuilder 在 JPA 2 中使用
coalesce
或 case statement
对于许多记录,initializedBy 将为空,因此这些记录的employeeName 将为空。对于那些数据库表中initializedBy 员工为空的项目,如果 employeeName
为空,我想显示
系统生成。
我在实体中有以下关系
项目
@Entity
@Table(name = "PROJECT")
public class Project {
@Id
@Column(name = "PROJECTID")
private Long projectId;
....
....
@ManyToOne
@JoinColumn(name = "EMPLOYEENUMBER", referencedColumnName = "EMPLOYEENUMBER")
private Employee empNumber;
@ManyToOne
@JoinColumn(name = "INITIATEDBY", referencedColumnName = "EMPLOYEENUMBER")
private Employee initiatedBy;
员工
@Entity
@Table(name = "EMPLOYEES")
public class Employee {
@Id
@Column(name = "EMPLOYEENUMBER")
private String employeeNo;
@Column(name = "EMPLOYEENAME")
private String employeeName;
.....
.....
@OneToMany(mappedBy = "empNumber")
private Set<Project> employeeProject;
@OneToMany(mappedBy = "initiatedBy")
private Set<Project> employeeInitiatedBy;
.....
在 DAOImpl 课程中我有
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Project> c = cb.createQuery(Project.class);
Root<Project> emp = c.from(Project.class);
c.orderBy(cb.desc(emp.get("projectNo")));
c.select(emp);
TypedQuery<Project> q = entityManager.createQuery(c);
我已经尝试过
Coalesce<String> coalesce = cb.coalesce();
coalesce.value(emp.<String>get("employeeName"));
coalesce.value("System Generated");
但是当我跑步时,我会遇到异常
java.lang.IllegalArgumentException: Unable to resolve attribute
[employeeName] against path
对此的任何帮助都非常值得赞赏。
第一个问题是在使用 JPA 实体作为查询结果时可能会产生误解。当实体用作查询结果时,它们反映数据库的状态。将
Employee.empName
替换为数据库中其他值与此相矛盾。
直到可以通过CriteriaBuilder.construct实现的某个点。结果对象(也可以是实体)是通过构造函数创建的,该构造函数必须将所有选择项作为参数。不幸的是,这与对象图(在本例中
Project
和连接的Employee
)配合得不好。
第二个问题是,下面的
get("employeeName")
被称为Project
,而它没有这样的属性:
Root<Project> emp = c.from(Project.class);
...
coalesce.value(emp.<String>get("employeeName"));
一般来说,coalesce可以按如下方式使用(但由于上面所说的,这并不能单独解决问题):
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> c = cb.createQuery(String.class);
Root<Employee> emp = c.from(Employee.class);
CriteriaBuilder.Coalesce<String> coalesce = cb.coalesce();
coalesce.value(emp.<String>get("employeeName"));
coalesce.value("System Generated");
c.select(coalesce);
TypedQuery<String> q = em.createQuery(c);