I had made class with java class name as “Employee” and db table name as “EMPLOYEE”. The table had many columns but i had declare only two variables on the employee class. Following is the code of Employee class:
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;
}
}
On the TestEmployee class, i had written the following code:
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());
}
}
}
Firstly, i am confusing whether to write “FROM EMPLOYEES” or “FROM Employee”.
Secondly, is it safe to declare the two variable in the POJO class (Employee) whereas there are many columns in the table.
Lastly, on executing the code I am facing the following exception:
Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: Employee is not mapped [FROM Employee]
My Database is locally installed (Oracle 10g XE)
HQL only uses entities, mapped properties and associations. Never tables and columns. So the correct query is
from Employee.If you don’t map all the table columns in your entity, every insert and update in the table will completely ignore the other columns. This means that they will keep their default or current values.
The exception you get, IIRC, means that you simply forgot to add the entity to the list of mapped entities in the hibernate configuration file.