简体   繁体   English

休眠-将多个多对一实体列

[英]hibernate - mutiple many-to-one to the same entity column

I have a relationship between buildings and floors: some floors can only be in 1 building (these floors will have only 1 foreign key to "building" table) and there are some floors sit between 2 buildings (these floors will have 2 foreign keys to "building" table, one is startBuildingId and the second is endBuildingId ).I have this code to represent this relationship: 我在建筑物和楼层之间有一个关系:有些楼层只能位于1栋建筑物中(这些楼层只有1个“建筑物”表的外键),有些楼层位于2栋建筑物之间(这些楼层将有2个外键用于“建筑”表,一个是startBuildingId ,第二个是endBuildingId 。我有这段代码来表示这种关系:

public class Building implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "building")
    private Set<Floor> floors = new HashSet<>();
}

public class Floor implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JsonIgnoreProperties("floors")
    @JoinColumn(name = "building_id")
    private Building building;

    @ManyToOne
    @JsonIgnoreProperties("")
    @JoinColumn(name = "start_building_id")
    private Building startBuildingId;

    @ManyToOne
    @JsonIgnoreProperties("")
    @JoinColumn(name = "end_building_id")
    private Building endBuildingId;
}

When I create a floor that is sits between 2 buildings, I've chosen the startBuildingId and endBuildingId , but when I retrieve all the floors from the building's private Set<Floor> floors , it only shows the other floors, not those floors that sit between 2 buildings. 当我创建一个位于两座建筑物之间的地板时,我选择了startBuildingIdendBuildingId ,但是当我从建筑物的private Set<Floor> floors检索所有private Set<Floor> floors ,它仅显示其他地板,而不显示那些位于的地板在2楼之间。 How can I achieve this? 我该如何实现?

My suggestion: 我的建议:

  • Three @OneToMany fields 三个@OneToMany字段
  • a method that returns a union of them 返回它们的并集的方法

I assume you don't do any modifications on the floors list (adding a Floor would not be clearly defined - does it belong to a single building, or is it shared). 我假设您不对楼层列表进行任何修改(添加楼层将无法明确定义-它是属于单个建筑物还是共享建筑物)。 In this case, it can be a lazy, unmodifiable view on the actual sets. 在这种情况下,它可能是实际集合上的一个懒惰的,不可修改的视图。

Alternatively (and preferably), you can easily create a JPQL/Criteria query that finds all the floors by building id. 另外(最好是),您可以轻松创建一个JPQL /条件查询,该查询通过建筑物ID查找所有楼层。

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

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