Fetching an object from the database

Now we will take a look at how to fetch objects using a Session. Here, we will also see how to get only one record using the primary key column. We override a toString() method in the Employee and Department classes so that it's easy to display the data within an object, as shown in the following code:

@Override
    public String toString() {
      return "\nEmployee"
      + "\n id: " + this.getId()
      + "\n first name: " + this.getFirstName()
      + "\n salary: " + this.getSalary()
      + "\n department: " + this.getDepartment().getDeptName();
    }

How to do it…

Here, we are trying to get an employee having id equals 1.

The equivalent SQL query is as follows:

SELECT * FROM employee WHERE id=1;

Now, let's look at how to do the same using hibernate: ...

Get Java Hibernate Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.