映射JPA实体关系 [英] Mapping JPA entity relationships

查看:63
本文介绍了映射JPA实体关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一些有关如何最佳布局我的JPA实体类的建议.假设我有两个要建模为实体,用户和角色的表.

I would like some advice on how to best layout my JPA entity classes. Suppose I have 2 tables I would like to model as entities, user and role.

Create Table users(user_id primary key,
                   role_id integer not null )
Create table role(role_id primary key,
                  description text,
                  )

我创建以下两个JPA实体:

I create the following two JPA Entities:

@Entity
@Table(name="users")
@Access(AccessType.PROPERTY)
public class User implements Serializable {
      private Long userId;
      private Long roleId;
      private Role role;

      @Column(name = "user_id")
      @Id
      public Long getUserId() {}

     @Column(name = "role_id")
      public Long getRoleId() {}

      @ManyToOne()
      JoinColumn(name="role_id")
      public Role getRole() {}
}

角色实体:

@Entity
@Table(name="Role")
@Access(AccessType.PROPERTY)
public class Role implements Serializable {
      private String description;
      private Long roleId;


      @Column(name = "role_id")
      @Id
      public Long getRoleId() {}

     @Column(name = "description")
      public Long getDescrition(){}

      @ManyToOne()
      @JoinColumn(name="role_id")
      public Role getRole() {}
}

对这种关系进行建模的正确方法是如上所述,还是我放弃私有的Long roleId?在用户中?任何意见的欢迎. 当我以这种方式进行映射时,会出现以下错误:

Would the correct way to model this relationship be as above, or would I drop the private Long roleId; in Users? Any advice welcomed. When I map it this way, I receive the following error:

 org.hibernate.MappingException: Repeated column in mapping for entity:

推荐答案

是的,当同一列上有@ManyToOne时,将删除private Long roleId映射.

Yes, you would drop the private Long roleId mapping when you have a @ManyToOne on the same column.

正如错误所暗示的,您只能将@Entity中的每一列映射一次.由于role_id@ManyToOne引用的@JoinColumn,因此您也不能将其映射为属性.

As the error implies, you can only map each column in an @Entity once. Since role_id is the @JoinColumn for the @ManyToOne reference, you cannot also map it as a property.

但是,您可以添加一个便捷方法来返回角色ID,例如

You can, however, add a convenience method to return the role ID, like

 public Long getRoleId() {
   return role.getId();
 }

这篇关于映射JPA实体关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆