0

I'm using hibernate for my project and what i'm essentially trying to do is figure out how to auto-map the values with foreign keys from my table in the database to a data object.

For example, I have a users table with the following columns

id - INT
username - VARCHAR
password - VARCHAR
email - VARCHAR
firstName - VARCHAR
lastName - VARCHAR

This is fairly straightforward to map as there are no foreign keys involved. The code I have is:

SQLQuery q = session.createSQLQuery("SELECT * FROM users WHERE username=? AND password=?");
            q.setString(0, username);
            q.setString(1, password);
            q.addEntity(User.class);

            List<User> users = q.list()

Now supposing I add some foreign keys to my user table such as

userlevel_id - INT
department_id - INT

Which reference the user level a user belongs to and the department. How do I get hibernate to map the user level name from the userlevel table and the department name from the department table? It wont be of much use if I just store the id's in the User data object as I will need to display the values to my views later on. Any help will be greatly appreciated, Thanks!!

1 Answer 1

1

Use an eagerly loaded @ManyToOne mapping on your User object. Make an object to represent both your Departmentand your UserLevel and add them as fields into your User object. The reason that you should have this mapping as eagerly loaded is that there is never a situation where you don't want to load a User without their Department or UserLevel. Hibernate will automatically map your User object to the appropriate Department and UserLevel.

If you want too, you can make the relationship bi-directional so you can get all users in a department by selecting a department. Anything you can do in SQL you can map using Hibernate.

Have a read of the documentation and see if that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.