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:
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. How can I achieve this?
My suggestion:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.