我正在尝试为支持多个位置的天气服务建模。我的应用程序包含3个实体:
位置-有关位置的信息
天气(包括位置ID)-一小时的天气数据
LocationWeather-Location的子类,包含天气列表
我希望“位置”有时作为“天气”的一个独立实体存在。这样一来,我就可以在Location对象上公开CRUD操作,而不会使其所有气象数据膨胀。但是,我仍然想满足给定位置返回天气的主要用例,这就是LocationWeather存在的原因。
继承可以做我想做的事吗?我试过了
@Entity
@Table(name="location")
@Inheritance(strategy = InheritanceType.JOINED)
public class Location {
但是我的子类(LocationWeather)不直接与表关联。我应该将“天气列表”上移到“位置”对象,并以某种方式将其标记为可选对象吗?
Location.java
@Entity
@Table(name="location")
public class Location {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="location_id")
private int id;
@Column(name="name")
private String name;
Weather.java
@Entity
@IdClass(WeatherId.class)
@Table(name="weather")
public class Weather {
@Id
@Column(name="location_id")
private int locationId;
@Id
@Column(name="time")
private Date time;
@Column(name="temperature")
private Double temperature;
LocationWeather.java
@Entity
public class LocationWeather extends Location{
@ElementCollection
@CollectionTable(name="weather", joinColumns= {@JoinColumn(name="location_id")})
@Column(name="weather")
private List<Weather> weather;
最佳答案
弄清楚了。我在搜索错误的东西。我应该一直在搜索“ 2个实体1个表”
我能够通过创建@MappedSuperclass并创建Location和LocationWeather作为其子类来解决该问题。
我现在有:
MappedLocation.java
@MappedSuperclass
public class MappedLocation {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="location_id")
private int id;
@Column(name="name")
private String name;
Location.java
@Entity
@Table(name="location")
public class Location extends MappedLocation {
}
LocationWeather.java
@Entity
public class LocationWeather extends MappedLocation{
@ElementCollection
@CollectionTable(name="weather", joinColumns= {@JoinColumn(name="location_id")})
@Column(name="weather")
private List<Weather> weather;
更多信息:https://thoughts-on-java.org/hibernate-tips-map-multiple-entities-same-table/