Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Spring with Hibernate File Uploads and Entity Updates in Spring + Hibernate Updating Categories: Part 1

When would do you use Category.class vs passing in a Category Object as a function parameter?

We passed in the Category object to the findById method in the CategoryDao as a Category.class .

        Category category = session.get(Category.class, id);

Why not pass it in as a function parameter as we did with the id?

1 Answer

Boban Talevski
Boban Talevski
24,793 Points

In the code you posted, we aren't passing the Category object, but the Category class as a first parameter to the method get (which you kinda said anyway :)). The thing is, we can't pass a Category object in its place because the method get requires a class to be passed as a first parameter, not an object. You can check the documentation here.

Note that the method get is a method of the Session class which is part of the Hibernate framework, so it's not like we have a choice, it's the way Hibernate works. There's an option to pass a string instead, which should be the fully qualified class name, in this case "com.teamtreehouse.giflib.model.Category", but it's essentially doing the same thing. Saying which class we want to "target" for this Category object.

My guess is that it's designed that way because somewhere under the hood that first parameter is actually used to point to a table in the database from which the information will be retrieved (along with the help of the Entity annotation on the class). Remember that we do have a plain old database in the background on which Hibernate is doing its magic by creating and executing SQL queries for us to fetch the data we want.