为可选的一对多关系建模-我应该使用继承吗?

时间:2019-05-08 21:44:13

标签: java spring-boot spring-data-jpa

我正在尝试对支持多个位置的天气服务进行建模。我的应用程序包含3个实体:

  1. 位置-有关位置的信息
  2. 天气(包括位置ID)-一小时的天气数据
  3. LocationWeather-包含天气列表的Location子类

我希望“位置”有时作为“天气”的独立实体存在。这样一来,我可以在Location对象上公开CRUD操作,而不会使其所有天气数据膨胀。但是,我仍然想满足给定位置返回天气的主要用例,这就是LocationWeather存在的原因。

继承可以完成我想做的事情吗?我尝试过

           <file-drop (click)="file.click()" dropZoneLabel="Drag & Drop file here!" (onFileDrop)="dropped($event)" (onFileOver)="fileOver($event)"
                (onFileLeave)="fileLeave($event)" disabled="true">
            </file-drop>

但是我的子类(LocationWeather)不直接与表关联。我应该将“天气列表”移到“位置”对象上,并以某种方式将其标记为可选对象吗?

Location.java

@Entity
@Table(name="location")
@Inheritance(strategy = InheritanceType.JOINED)
public class Location {

Weather.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;

LocationWeather.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;

1 个答案:

答案 0 :(得分:0)

弄清楚了。我在搜索错误的内容。我应该一直在搜索“ 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/