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:
Enter the following code to fetch an object of the
employee
type, where theid
is1
:SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); Employee...