具有 Table 和实体映射的 Hibernate 查询异常

Hibernate Query Exception with Table and Entity Mapping

我收到如下错误:

org.hibernate.hql.internal.ast.QuerySyntaxException: Employee is not mapped [from Employee]; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Employee is not mapped [from Employee]",
    "trace": "org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.ast.QuerySyntaxException: Employee is not mapped [from Employee];

我创建了如下所示的模式

@Entity
@Table(name="employee_list")
public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column
    private Integer id;

    @Column
    private String name;

    @Column
    private String gender;

    @Column
    private String department;

    @Column
    private Date dob;
    // getters/setters
}

My Dao 实现:

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<Employee> get() {
        Session currentSession = entityManager.unwrap(Session.class);
        Query<Employee> query =  currentSession.createQuery("from Employee", Employee.class);
        List<Employee> list = query.getResultList();
        return list;
    }
}

我遗漏了一些东西。
我无法确定具体是什么。

HQL 应该如下所示:

currentSession.createQuery("select e from Employee e", Employee.class);

此外,您可以使用 条件 API:

currentSession.createCriteria(Employee.class).list();

有用的参考资料:

尝试将 @EntityScan(basePackage="*the package where your entity lies*")(或类似)注释添加到您的 EmployeeDAOImpl class。查询看起来没问题。对于 HQL,您必须使用类型名称,而不是 table 名称。 如果您正在使用 Spring JPA,您还可以尝试使用提供的接口,如 JPARepository 或 CrudRepository

@Entity 应该来自 JPA 库,而不是 hibernate 库。而且,您应该在查询中使用实体名称:

session.createQuery("from Employee", Employee.class);