Search code examples
hibernatenamed-query

I have a issue in hibernate namedquery


I'm using annotation for named query in hibernate.I have two classes a POJO class and a main class.The POJO class is as follows

@NamedQuery(
    name="findEmployeeName",
    query="select * from employee " 
)


@Entity
@Table(name="employee")
public class Employeenam {
    public String tostring(){return id+" " +name+ " " +salary+ " " +job;}

    @Id
    @GeneratedValue
    @Column(name="id")
    int id;

    @Column(name="name")
    String name;

    @Column(name="salary")
    int salary;

    @Column(name="job")
    String job;

    public int setempId(){
        return id;
    }

    public void getempId(int Id){
        this.id=Id;
    }

    public String setempName(){
        return name;
    }

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

    public int getempSalary(){
        return salary;
    }

    public void setempSalary(int Salary){
        this.salary=Salary;
    }

    public String setempJob(){
        return job;
    }

    public void getempJob(String Job){
        this.job=Job;
    }
}

and the main class as follows

    public class FetchData{
    public static void main(String[] args){

        Configuration configuration=new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory sfactory=configuration.buildSessionFactory();
        Session session=sfactory.openSession();
        Query query=session.getNamedQuery("findEmployeeName");
        query.setString("name", "dfdsf");
        query.setInteger("id", 34);
        query.setInteger("salary", 3543);
        query.setString("job", "dfgere");       
        session.close();
    }
    }

when i try to run this iam getting the following error

Exception in thread "main" org.hibernate.HibernateException: 
Errors in named queries: findEmployeeName

can anyone tell me where i am going wrong?? I'm kind of new to hibernate..so please forgive me for any obvious errors....


Solution

  • With HQL, you should reference entities instead of tables. So, it should be Employeenam instead of employee. If you're setting parameters to the query, you should also be using them in the query, making reference to the property names, according to the getters/setters (for instance, empSalary).

    Try to write your query like this:

    from Employeenam 
    where empname = :name 
        and empid = :id 
        and empsalary = :salary 
        and empjob = :empjob
    

    Also, you might consider changing your property names to match the getters/setters. If the property is called id, the corresponding getter/setter should be getId()/setId(id).