在JPA中使用Coalesce或Case语句

时间:2013-07-29 10:46:18

标签: hibernate jpa jpa-2.0 criteria-api coalesce

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

对于许多已启动的记录,它们将为空,因此对于这些记录,employeeName将为null。如果employeeName对于那些在数据库表中为initiateBy employee为null的项目,我想显示系统生成

我在实体中有以下关系

项目

@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

对此的任何帮助都非常值得赞赏。

1 个答案:

答案 0 :(得分:9)

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

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

第二个问题是,在get("employeeName")中调用了Project,并且它没有这样的属性:

Root<Project> emp = c.from(Project.class);
...
coalesce.value(emp.<String>get("employeeName"));

一般来说,合并可以如下使用(但由于上面所说的,这并不能单独解决问题):

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);