我有以下命名查询
select new test.entity.Emp(COALESCE(k.projectId,'N')
as projectId, k.projectName) from Emp o inner join o.projects k
但是我收到错误
期待 RIGHT_ROUND_BRACKET,发现 '('
COALESCE
在namedQuery中如何处理?
有没有其他方法可以在 JPA 中处理空值?
JPA 2.0 API 支持Coalesce 。
该new
构造是 Hibernate 专有的,不一定在所有 JPA 实现中都支持。首先尝试查询而不尝试构造对象:
select COALESCE(k.projectId,'N') as projectId, k.projectName from Emp o inner join o.projects k
你的括号弄乱了,或者你有一个多余的别名子句,当你正确缩进你的语句时很容易看到。
select
new test.entity.Emp(
COALESCE(k.projectId,'N') as projectId,
k.projectName
)
from Emp o inner join o.projects k
试试这个:
select
new test.entity.Emp(
COALESCE(k.projectId,'N'),
k.projectName
)
from Emp o inner join o.projects k
我尝试了以下简单的单元测试,成功通过:
@Test
public void coalesceTest() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
DepartmentEmployee employee = new DepartmentEmployee();
EmployeeDepartment department = new EmployeeDepartment();
department.getEmployees().add(employee);
employee.setDepartment(department);
transaction.begin();
try {
entityManager.persist(employee);
entityManager.persist(department);
transaction.commit();
Assert.assertTrue("Employee not persisted", employee.getId() > 0);
Assert.assertTrue("Department not persisted", department.getId() > 0);
} catch (Exception x) {
if(transaction.isActive()) {
transaction.rollback();
}
Assert.fail("Failed to persist: " + x.getMessage());
}
TypedQuery<String> query = entityManager.createQuery("select coalesce(e.name, 'No Name') from EmployeeDepartment d join d.employees e", String.class);
String employeeName = query.getSingleResult();
Assert.assertEquals("Unexpected query result", "No Name", employeeName);
}
部门雇员类:
@Entity
public class DepartmentEmployee implements Serializable {
@Id
@GeneratedValue
private int id;
private String name;
@ManyToOne
private EmployeeDepartment department;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeDepartment getDepartment() {
return department;
}
public void setDepartment(EmployeeDepartment department) {
this.department = department;
}
}
员工部门类:
@Entity
public class EmployeeDepartment implements Serializable {
@Id
@GeneratedValue
private int id;
@OneToMany
private List<DepartmentEmployee> employees;
public EmployeeDepartment() {
employees = new ArrayList<DepartmentEmployee>();
}
public int getId() {
return id;
}
public List<DepartmentEmployee> getEmployees() {
return employees;
}
public void setEmployees(List<DepartmentEmployee> employees) {
this.employees = employees;
}
}
使用 EclipseLink 2.5.0 测试:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>