【问题标题】:Issue in Mapping for Hibernate JPAHibernate JPA 的映射问题
【发布时间】:2014-01-31 04:17:24
【问题描述】:

我有一个数据模型,它有:

  • User 实体,其中有几个字段特定于应用程序中的 2 个用户
  • 另一个实体UserDetails,除了User实体中的字段之外,它还包含特定于应用程序中一种特定类型用户的详细信息

两个实体共享相同的主键。我是 JPA 的新手。两者之间应该有什么样的映射关系?

@Entity
class User{
  @Id
  @Column(name="USER_ID")
  private int id;
}


@Entity
class UserDetails{
  @Id
  @OneToOne(optional = false, fetch = FetchType.EAGER)
  @JoinColumn(name = "USER_ID")
  private User user;

  ...
}

上述映射在为特定User 获取UserDetails 时出现问题。

要求两个实体共享相同的主键 USER_ID。

【问题讨论】:

    标签: java hibernate jpa-2.0 hibernate-mapping


    【解决方案1】:

    您没有提到上述映射的问题。看起来不错,但我会为 UserDetails 表使用单独的主键。

    @Entity
    class UserDetails{
      @Id
      private int id;
    
      @OneToOne(optional = false, fetch = FetchType.EAGER)
      @JoinColumn(name = "USER_ID")
      private User user;
    
      ...
    }
    

    此外,使用bidirectional relationships 是一个好习惯,为了更轻松地导航,即从User 获取用户详细信息,您只需在User 类中使用user.getUserDetails();

    @Entity
    class User{
      @Id
      @Column(name="USER_ID")
      private int id;
    
      @OneToOne(mappedBy = "user")
      private UserDetails userDetails;
    }
    

    【讨论】:

    • 实际上数据模型要求两者共享主键,即 USER_ID 是两个实体的主键。在上述情况下获取用户列表时,我得到一个空输出,而 DB 中的表在用户中有行。
    【解决方案2】:

    在这种情况下,使用OneToOne 关系。但请确保您的数据库表UserDetailsUser 表有外键关系。使用下面的代码使用JPAHibernate 来实现它。

    @Entity
    class User{
      @Id
      @Column(name="USER_ID")
      private int id;
    
      // getters and setters
    }
    
    
    @Entity
    class UserDetails{
      @Id
      @Column(name="USER_DETAILS_ID")
      private int userDetailsId;
    
      @OneToOne(optional = false, fetch = FetchType.LAZY)
      @JoinColumn(name = "USER_ID")
      private User user;
    
      // getters and setters
    }
    

    【讨论】:

    • 实际上数据模型要求两者共享主键,即 USER_ID 是两个实体的主键。在我提到的案例中获取用户列表时,我得到一个空输出,而 DB 中的表在用户中有行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多