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()?

Ali
  • 261,656
  • 265
  • 575
  • 769

2 Answers2

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.

Peter Bratton
  • 6,302
  • 6
  • 39
  • 61
  • 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 ? – Ali Feb 26 '14 at 14:33
  • 1
    @ManyToOne. You pretty much answered yourself :) – Peter Bratton Feb 26 '14 at 14:35
  • yeah, i realized that at the end but had typed the comment by then :). any chance you could look at this too: http://stackoverflow.com/questions/21971272/how-to-save-enum-value-to-db-with-hibernate?rq=1 – Ali Feb 26 '14 at 14:41
  • The answers there look good. Also check out the linked possible duplicate question. – Peter Bratton Feb 26 '14 at 14:43
  • Sorry, I linked to the wrong question. Here's what I had meant for you to look at: http://stackoverflow.com/questions/22042903/how-to-use-enum-members-in-a-hibernate-entity-class – Ali Feb 26 '14 at 14:48
  • Question. If I have one table called `user`, and another called `user_inbox`, where I have a list of messages, each message has a `userId` column which refers to the `user.id` column. In that case, how would I map that? – Ali Feb 26 '14 at 16:39
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.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99