BiswajitP
BiswajitP

Reputation: 233

Hibernate: many to one mapping with two table

I have two tables Users(id,name,email,role_id) and role(id,type) I am using @ManyToOne (cascade=CascadeType.ALL) role in user bean Because of it a new role is getting inserted every time. But I want user to use existing entry of role table. Please help

Upvotes: 0

Views: 189

Answers (4)

Yogesh
Yogesh

Reputation: 4784

Considering both the id columns in users and role are primary key, what you need is when persisting new user first retrieve desired role by it's type from database and then just set that role in user entity and persist that user.

Upvotes: 0

Koitoer
Koitoer

Reputation: 19543

I suppose

@Entity
public class Users{
  @Id
  private int id;
  private String email;
  @ManyToOne(cascade=CascadeType.ALL)
  private Role role_id;
}

@Entity
public class Role{
    @Id
    private int id;
    private String type;
 } 

Using JPA

Create roles first

Role role1 = new Role(1,"Role1");
Role role2 = new Role(2,"Role2");

Then add the role to the user

User user1 = new User(1,"User1","mail",role1);

EntityManager em = ....
em.persist(user1);

As we have cascade option role1 and user1 will be saved in the database, dont forget to use a transaction to do this operation

If you want to use a pre-existing Role consider retrieve it first from database

Role existingRole = em.find(Role.class, 1);
User user1 = new User(1,"User1","mail",existingRole );

EntityManager em = ....
em.persist(user1);

Upvotes: 1

Sinto
Sinto

Reputation: 930

Keep a separate @Column for role_id in Users apart from the one annotated with @ManyToOne then set the role_id to Users and persist Users. You dont need a cascade so remove it to have casacade type as none rather than ALL. In the @ManyToOne you should give insertable=false & updatable=false to avoid repeated column issue.

See this example

Upvotes: 0

Vitaly
Vitaly

Reputation: 2800

You need to find the existing Role object first and then set it into User object.

In other words, the Role object needs to be already created and managed before you save User.

Upvotes: 1

Related Questions