简体   繁体   English

Hibernate:使用两个表进行多对一映射

[英]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. 我有两个表Users(id,name,email,role_id)role(id,type)我在用户bean中使用@ManyToOne (cascade=CascadeType.ALL)角色因为它每次都会插入一个新角色。 But I want user to use existing entry of role table. 但我希望用户使用角色表的现有条目。 Please help 请帮忙

You need to find the existing Role object first and then set it into User object. 您需要先找到现有的Role对象,然后将其设置为User对象。

In other words, the Role object needs to be already created and managed before you save User. 换句话说,在保存用户之前,需要已创建和管理Role对象。

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 使用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 由于我们有级联选项role1而user1将保存在数据库中,所以不要忘记使用事务来执行此操作

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);

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. 除了使用@ManyToOne注释的用户之外,在用户中为role_id保留单独的@Column,然后将role_id设置为Users并持久保存用户。 You dont need a cascade so remove it to have casacade type as none rather than ALL. 你不需要级联所以删除它以使casacade类型为none而不是ALL。 In the @ManyToOne you should give insertable=false & updatable=false to avoid repeated column issue. 在@ManyToOne中,您应该给出insertable = false&updatable = false以避免重复列问题。

See this example 看这个例子

考虑到用户和角色中的id列都是主键,您需要的是当持久新用户首先通过数据库中的类型检索所需角色,然后在用户实体中设置该角色并保留该用户时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM