我的JPA Criteria API代码(取自JEE6教程)有什么问题?

时间:2010-10-04 16:13:56

标签: java hibernate jpa

这是我的代码,我甚至无法编译:

/**
 * Find a project that has NO employee assigned yet.
 */
public Project findEmptyProject() {
  // getting criteria builder
  CriteriaBuilder cb = this.em.getCriteriaBuilder();
  // gathering meta information about left-joined entity
  Metamodel m = this.em.getMetamodel();
  EntityType<Employee> Employee_ = m.entity(Employee.class);
  // creating query
  CriteriaQuery<Project> cq = cb.createQuery(Project.class);
  // setting query root for the query
  Root<Project> project = cq.from(Project.class);
  // left-joining with another employees
  Join<Employee, Project> projects = project.join(
    Employee_.project, 
    JoinType.LEFT
  );
  // instructing the query to select only projects
  // where we have NO employees
  cq.select(project).where(Employee_.id.isNull());
  // fetching real data from the database
  return this.em.createQuery(cq).getSingleResult();
}

我的模型类是:

public class Employee {
  @Id private Integer id;
  @ManyToOne private Project project;
  private String name;
}

public class Project {
  @Id private Integer id;
  private String name;
}

编译器说(我会说同样是编译器):

Finder.java: cannot find symbol: variable project
location: interface javax.persistence.metamodel.EntityType<com.XXX.Employee>

我做错了什么?

1 个答案:

答案 0 :(得分:3)

当您使用Employee_.project语法时,Employee_必须是自动生成的元模型类,而不是通过EntityType获得的Metamodel.entity()

Hibernate JPA 2 Metamodel Generator manual解释了如何在Hibernate中配置这些类的生成。