0

I had made select query in hibernate from employees table that had following columns:

private int id;
    private String firstname;
    private String lastname;
    private String email;
    private String phoneno;
    private Date hiredate;
    private Jobs jobid;
    private Integer salary;
    private Integer commpct;
    private Employee managerid;
    private Departments deptid;

On this table, first record had managerid set to null, and afterwards every record managerid set to first record employeeid;

when i select data from employees table using query: ("FROM EMPLOYEES") using following code:

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()
                    +"\temail=>"+employee.getEmail()+"\tPhoneNO=>"+employee.getPhoneno()+"\tHireDate=>"+employee.getHiredate()
                    +"\tJob=>"+employee.getJobid().getJobtitle()+"\tMax Salary=>"+employee.getJobid().getMaxsalary()
                    +"\tPresent Salary=>"+employee.getSalary()+"\tCommission %=>"+employee.getCommpct()+"\tManager=>"+employee.getManagerid().getFirstname()+","+employee.getManagerid().getLastname()
                    +"\tDepartment ID=>"+employee.getDeptid().getName());

        }

Exception throws bcoz first record managerid is null,

Then, i used this query

Query query = session.createQuery("FROM Employee em WHERE em.managerid IS NOT NULL AND em.deptid IS NOT NULL");

I get the record other than first record.

ID is the primarykey and managerid is the foreign key pointing to Employees Table (id) field. All rows have id present but some rows/one row had managerid set to null.

My Question is how to get all the records even if first record managerid is set to null?

What setting i had to made?

spring pro
  • 107
  • 4
  • 12

1 Answers1

0

First of all, in hibernate entities it is mandatory to have primary key column in table & it has to be not null. Else hibernate can't handle entities as it handles them using primary key. So null primary key is confusing to hibernate so not allowed.

You can fire native query using hibernate if you want to anyways fetch the data.

Native query Reference: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html

Ravi K
  • 976
  • 7
  • 9
  • 1
    Ohh ok. It's classic case of inner vs outer join in hibernate. In that case your answer is in this post: http://stackoverflow.com/questions/1525098/hibernate-default-joining-for-nullable-many-to-one – Ravi K Oct 26 '12 at 09:04