4

如何使用coalescecase statement在 JPA 2 中使用 CriteriaBuilder

对于许多记录,initiatedBy 将为空,因此这些记录的employeeName 将为空。对于那些在数据库表中 InitialBy 员工为空的项目,我想显示System Generated if为空。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

对此的任何帮助都是非常可观的。

4

1 回答 1

13

第一个问题是在使用 JPA 实体作为查询结果时可能存在误解。当实体被用作查询的结果时,它们反映了数据库的状态。Employee.empName用数据库中的值以外的值替换与此相矛盾。

直到可以通过CriteriaBuilder.construct实现的某个点。结果对象(也可以是实体)是通过构造函数创建的,该构造函数必须将所有选择项作为参数。不幸的是,这与对象图(在这种情况下是Project连接的)一起不能很好地发挥作用。Employee

第二个问题是 in following get("employeeName")is called for 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);
于 2013-07-29T19:23:23.683 回答