So let's now create a new program to retrieve the same category based on the ID. So let's right click new class. And then I'm going to change this to 02. I call the class as main, press enter. I forgot to select the Add main function. So I'm going to type here main control space and select the main method over here.
I'm going to say here factory equals to hibernate util dot get session factory, press Control one or Command one on Mac, and then I get the session factory and also are here at try finally lock. And inside this finally block, I'm going to say factory dot close. And then I also like to save your session equals to factory dot open session. We haven't created the session variable. Let's create that by pressing Command one, and then I got that somewhere at the end. I also have to say efficient close unlike the previous example, where we inserted a new record Which is qualified as DML, which is supposed to be given in a transactional boundary.
Select statements, on the other hand, do not require transactions. Now, in order to get data from the DB, all we need is the primary key value of the table that we have, which is categories. And the ID here is one, we can just come down here and then say session dot get. And we can say what is the object that we want hibernate to give us, that's going to be category dot class. And that's from our entity package. And the ID here is one which is the primary key value.
This returns a new category object. At this point in time, hibernate is going to read the metadata from this category Java, such as table names, column names, etc. and generate an SQL SELECT statement based on the primary key value compared with this one here. And then it retrieves the data gets a result set converts that result set into a category object returns the category object to me here. Again, I have to create this variable i press Command one, enter, I got the new category object. Once the session is closed, I can still access that c one by typing c one over here.
So if I save this and run the program, I should be able to see a select statement as well as the values from the DB. So this is the select statement that got generated. And this is the category object that we have retrieved from the DB