0

Say I have a Role type, which contains a long id, String name, etc. And I have another User class. Each user will have a roleId column which will point to Role.id.

In my database I will 2 tables, one for user, the other for role. The roleId in the user table will be a foreign key to role.id table.

My question is, how can I map this in Hibernate, so that I'll be able to have a Role role column in my User class, and would be able to do things like user.getRole().getName()?

2 Answers 2

2

From the manual:

Many-to-one associations are declared at the property level with the annotation @ManyToOne:

 @Entity
 public class User {
     @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
     @JoinColumn(name="roleId")
     public Role getRole() {
         return role;
     }
     ...
 }

The @JoinColumn attribute is optional, the default value(s) is like in one to one, the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column in the owned side. In this example company_id because the property name is company and the column id of Company is id.

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

6 Comments

in this case, where i have multiple roles, but each user will only have 1 role at a time, am i looking at ManyToOne or ManyToMany ?
@ManyToOne. You pretty much answered yourself :)
yeah, i realized that at the end but had typed the comment by then :). any chance you could look at this too: stackoverflow.com/questions/21971272/…
The answers there look good. Also check out the linked possible duplicate question.
Sorry, I linked to the wrong question. Here's what I had meant for you to look at: stackoverflow.com/questions/22042903/…
|
1

Simply declare yor fields as related entities so your User class would have private Role role field or limilar, annotated with proper @OneToX annotation.

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.