我用java类名作为“Employee”,db表名为“EMPLOYEE”。该表有很多列,但我在employee类中只声明了两个变量。以下是Employee类的代码:
package com.mmi.education;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="EMPLOYEES")
public class Employee {
private int id;
private String firstname;
private String lastname;
@Id
@Column(name="EMPLOYEE_ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="FIRST_NAME")
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
@Column(name="LAST_NAME")
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
在TestEmployee类中,我编写了以下代码:
package com.mmi.education;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class TestEmployee {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AnnotationConfiguration config= new AnnotationConfiguration();
config.configure("hibernate.cfg.xml");
SessionFactory factory = config.buildSessionFactory();
Session session = factory.getCurrentSession();
//session.beginTransaction();
Query query = session.createQuery("FROM Employee");
List<Employee> employees = query.list();
for(Employee employee:employees){
System.out.println("ID=>"+employee.getId()+"\tFirstName=>"+employee.getFirstname()+"\tLastName=>"+employee.getLastname());
}
}
}
首先,我很困惑是否写“FROM EMPLOYEES”或“FROM Employee”。 其次,在POJO类(Employee)中声明两个变量是否安全,而表中有许多列。
最后,在执行代码时,我遇到以下异常:
Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: Employee is not mapped [FROM Employee]
我的数据库是本地安装的(Oracle 10g XE)
答案 0 :(得分:1)
HQL仅使用实体,映射属性和关联。从不表和列。所以正确的查询是from Employee
。
如果未映射实体中的所有表列,则表中的每个插入和更新都将完全忽略其他列。这意味着他们将保留默认值或当前值。
您获得的异常IIRC意味着您只是忘记将实体添加到hibernate配置文件中的映射实体列表中。