HQL查询未按预期工作

时间:2013-12-19 06:05:30

标签: hibernate jpa hql ejb-3.0 jpql

我的服务器端组件是EJB和JPA。

我的实体看起来如下

@Entity
@Table(name = "employee")
public class Employee implements Serializable {

private static final long serialVersionUID = 4235645698986231545L;

@EmbeddedId
private EmployeeId id;

@Column
private String designation;

public Employee() {
}

public EmployeeId getId() {
    return this.id;
}

public void setId(EmployeeId id) {
    this.id = id;
}


public String getDesignation() {
    return this.designation;
}

public void setDesignation(String designation) {
    this.designation = designation;
}

}

嵌入式实体

@Embeddable
public class EmployeeId implements java.io.Serializable {

private static final long serialVersionUID = 4542369821217566566L;

@Column(name = "emp_id")
private Integer empId;

@Size(max = 10)
private String name;


public EmployeeId() {
}


public Byte getEmpId() {
    return this.empId;
}

public void setEmpId(Integer empId) {
    this.empId = empId;
}

public String getName() {
    return this.stationId;
}

public void setName(String name) {
    this.name = name;
}

}

我的表看起来像这样

雇员

======

emp_id | name | designation |
==============|==============
1001   | xxxx | programmer  |
1001   | yyyy | programmer  |
1002   | zzzz | tester      |
1003   | aaaa | HR          |
1004   | bbbb | Admin       |
1005   | cccc | Manager     |
1006   | dddd | programmer  |
1007   | eeee | programmer  |
1008   | ffff | programmer  |
1008   | gggg | programmer  |
=============================

我的JPQL查询是

String query = "from Employee where designation = :design ";

public List<Employee> find(String designation) {

     return getEntityManager().createQuery(query).setParameter("design", designation).getResultList();
 }

我的预期结果如下。我在手动查询时得到了这个

emp_id | name | designation |
==============|==============
1001   | xxxx | programmer  |
1001   | yyyy | programmer  |
1006   | dddd | programmer  |    6 rows
1007   | eeee | programmer  |
1008   | ffff | programmer  |
1008   | gggg | programmer  |
=============================

但我得到的是通过JPQL输出

emp_id | name | designation |
==============|==============
1001   | xxxx | programmer  |
1001   | xxxx | programmer  |    6 rows
1001   | xxxx | programmer  |
1001   | xxxx | programmer  |
1001   | xxxx | programmer  |
1001   | xxxx | programmer  |
=============================

为什么它提供重复值但行数正确?有什么问题我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我之前没有看过没有 select关键字的编写的JPQL select语句;我不能确切地说这是错误的,但您可能会尝试按如下方式重新构建查询:

String query = "select e from Employee e where e.designation = :design ";

我还建议用类名“Employee”替换表名“employee”(如上所示)。同样,我不知道你在做什么是错的,但我总是使用(不合格的)Java类名而不是我的JPQL中的表名。

以下是一些示例:http://en.wikibooks.org/wiki/Java_Persistence/JPQL#Select_query_examples