Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNelson Fleig
25,764 PointsWhen 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
24,793 PointsIn 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.