This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
I have a created two entities called User and Role. A user can have many roles and a role can have many users.
Now I got three tables. ie app_user (User) table, role table and user_role table.
Now, we know that the user_role does not have entity class (model). When I write in my DAOHibernate, I want to get access to this user_role table in order to get a list of username having role as 'user'. How can I write it in my code....
I hope I made my doubt clear to you all. So Please help . Thank you.
So, you're basic question is "how do I get to the join table?" Well, essentially, you don't! The join table is a database artifact, but there's really no equivalent, object oriented term or artifact in Java. That's sorta why we need Hibernate - so we can solve our problems using Java terms, technology and facilities, and not have to burden ourselves with that whole silly and non-sensical world database developers have created around their little databases.
What you want to do is find all the User's who are in a certain role, or all of the Role's a certain user is in, correct?
Well, one easy way might just be do do a criteria query using an example object. You could create a Role, User user = new User();
Then, you could set a property, such as user.setRole("Cherry Picker");
Then just perform the criteria query. It might look like this.
So, as you can see, we never actually get to the join table. Instead, we maintain an object oriented approach to our problem domain. Hibernate then translates this object oriented approach to the relational database environment.
I have a few Hibernate examples that use the criteria API on my website that might help you out. That is where I copied this code:
You've actually caught me on what I think is one of the toughest things about learning Hibernate. It seems that every example uses a HibernateUtil class to hide the underlying plumbing of creating a Session, which is necessary in examples, but at the same time, people who are new to Hibernate are easily left with the impression that HibernateUtil is part of the API, which it is not. As you've found out, you need to create your own.
To be honest, I don't even like the name HibernateUtil. I prefer HibernateService, or something like that, but what can you do.
Here's a very, very scaled down, non-production ready, HibernateUtil class in case anyone is looking for one.
Thanks for the help. I just want your opinion. Does your book covers all the Hibernate details like the hardcore one "java persistence with Hibernate" by Christain Bauer and Gavin King. To be honest, this hardcore book is pretty much tough for beginners like me.