Ali
Ali

Reputation: 267077

How to embed another entity in a Hibernate entity using its id?

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

Upvotes: 0

Views: 1565

Answers (2)

Antoniossss
Antoniossss

Reputation: 32517

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

Upvotes: 1

Peter Bratton
Peter Bratton

Reputation: 6408

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.

Upvotes: 2

Related Questions