【问题标题】:OneToMany with composite key具有复合键的 OneToMany
【发布时间】:2018-05-29 10:47:17
【问题描述】:

我有 2 类 User 和 Bottom , User 与 Bottom 有很多关系。 用户有 2 个复合键

用户ID

class TireId {
 private String uId;
 private String schoolId
}

用户实体:

@IdClass(UserId.class)
@Entity
Class User {

 @Id
 private String uId;
 @Id
 private String schoolId

    @OneToMany(mappedBy="user")
    private List<Bottom> bottoms;


}

底部标识:

class BottomId {
   private String bId;
   private String cId;
   private String schoolId;

}

底层:

@IdClass(BottomId.class) 
@Entity
class Bottom {
    private String bId;
   private String cId;
   private String schoolId;
    @ManyToOne
   private  User user;
}

在上述情况下,hibernate 将在底部表名 user_uId 和 user_schoolId 中创建 2 个附加列。

但我需要用户 oneToMany 与以下关系的关系

schoolId of user == schoolId of Bottom
and uId of user == cId of of Bottom

如何存档?

【问题讨论】:

    标签: hibernate jpa


    【解决方案1】:

    这是一个“派生身份”,所以BottomId 应该是这样的:

    class BottomId {
        private String bId;
        private UserId user; // matches name of attribute and type of User PK
    }
    

    Bottom 应该这样映射:

    @IdClass(BottomId.class) 
    @Entity
    class Bottom {
        @Id
        private String bId;
    
        @Id
        @JoinColumns({
            @JoinColumn(name="cId", referencedColumnName="uId"),
            @JoinColumn(name="schoolId", referencedColumnName="schoolId")
        })
        @ManyToOne
        private  User user;
    }
    

    在 JPA 2.1 规范的第 2.4.1 节中讨论了派生的身份(带有示例)。

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2015-07-02
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      • 2012-02-28
      • 2014-07-01
      相关资源
      最近更新 更多