【问题标题】:Hibernate many to many mapping for multiple relationships between two entities with linking table休眠多对多映射,用于具有链接表的两个实体之间的多个关系
【发布时间】:2021-08-07 22:32:35
【问题描述】:

我正在处理一个自行车租赁申请,关系如下:

因此,基本前提是注册用户既可以出租他的自行车,也可以租用某人的自行车,而自行车又可以出现在要约和出租中(我将设置一些检查确保自行车可用或出租,但不能同时提供)。

我的 Hibernate 是垃圾,所以我正在寻找一个合理的对象映射来处理上述情况。到目前为止,我认为类结构看起来像这样:

@Entity(name = "user")
@Table(name = "user")
public class User {
    @Id
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;
    ...
}
@Entity(name = "bike")
@Table(name = "bike")
public class Bike {
    @Id
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;
    ...
}    
@Entity(name = "bike_offer")
@Table(name = "bike_offer")
public class BikeOffer {
    @OneToOne()
    private User lender;
    @OneToMany
    private Bike bike;
    ...
}
@Entity(name = "bike_hire")
@Table(name = "bike_hire")
public class BikeHire {
    @OneToOne()
    private User lender;
    @OneToMany
    private Bike bike;
    ...
}

我可以立即看到这行不通,因为我需要为 @OneToOne 和 @OneToMany 关系指定 @JoinTable,但我不确定要指定哪一个,因为我已经声明了 @987654327 @ 和 BikeHire 作为与表的关系。

所以我被困住了。关于如何将这种双重关系作为实体解开的任何建议?

【问题讨论】:

  • BikeHire extends User 表示 BikeHire 是用户。 Bike 和 User 不应该是抽象的。 User 类(或 Bike 类,或两者兼有)还应具有 BikeHire 集合和 BikeOffer 集合。
  • 谢谢 Guillaume,实际上抽象类和 BikeHire 扩展用户是复制和粘贴错误。我已经编辑了我的帖子来解决这些问题。谢谢你——你的建议实际上让我走上了正轨。

标签: java hibernate entity-relationship


【解决方案1】:

感谢@Guillaume,这是解决方案。都在 User 类中:

@Entity(name = "bike")
@Table(name = "bike")
public class Bike {
    @Id
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;
    ...
}    

@Entity(name = "user")
@Table(name = "user")
public class User {
    @Id
    @Column(name = "user_id", updatable = false, nullable = false)
    private UUID id;
    ...
    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "bike_offer",
            joinColumns = @JoinColumn(name = "user_id", foreignKey=@ForeignKey(name="bike_offer_user_id")),
            inverseJoinColumns = @JoinColumn(name = "bike_id", foreignKey=@ForeignKey(name="bike_offer_bike_id"))
    )
    private Set<Bike> bikeOffers;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "bike_hire",
            joinColumns = @JoinColumn(name = "user_id", foreignKey=@ForeignKey(name="bike_hire_user_id")),
            inverseJoinColumns = @JoinColumn(name = "bike_id", foreignKey=@ForeignKey(name="bike_hire_bike_id"))
    )
    private Set<Bike> bikeHires;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    相关资源
    最近更新 更多