我有以下关系

java - 如何对包含外键的复合主键建模?-LMLPHP

如您所见,feature_affinities的详细信息表具有组合键(feature_idzoom),其中的组成部分是外键,引用了features的主表。

我写

@Entity
@Table(name = "features")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "subtype_id", discriminatorType = DiscriminatorType.INTEGER)
public class Feature {

   @Id
   @Column(name="id")
   @GeneratedValue(generator="sqlite")
   @TableGenerator(name="sqlite", table="sqlite_sequence",
      pkColumnName="name", valueColumnName="seq",
      pkColumnValue="features")
//   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Getter
   @Setter
   private long id;

...

@Embeddable
public class FeatureAffinitiesKey implements Serializable {

   @ManyToOne
   @JoinColumn(name = "feature_id")
   @Getter
   @Setter
   private Feature feature;

   @Column(name = "zoom")
   @Getter
   @Setter
   private Long zoom;
}

@Entity
@Table(name = "feature_affinities")
public class FeatureAffinities {

   @Getter
   @Setter
   @EmbeddedId
   private FeatureAffinitiesKey key;

...


它是否正确?

我很困惑,它要求我声明FeatureAffinitiesKey可序列化。但是,由于它包含Feature字段,因此将导致Feature也应该可序列化,并且Feature中的所有与化合物相关的类也应可序列化。

这正常吗?

最佳答案

这就是JPA规范所称的“派生身份”。您应该对FeatureAffinities类的定义稍有不同:

@Embeddable
public class FeatureAffinitiesKey implements Serializable {

   @Column(name = "feature_id")
   @Getter
   @Setter
   private long featureId; // corresponds to the type of Feature's PK

   @Column(name = "zoom")
   @Getter
   @Setter
   private Long zoom;
}

@Entity
@Table(name = "feature_affinities")
public class FeatureAffinities {

   @Getter
   @Setter
   @EmbeddedId
   private FeatureAffinitiesKey key;

   @MapsId("featureId") // maps 'featureId' attribute of embedded id
   @ManyToOne
   @Getter
   @Setter
   private Feature feature;

   ...
}


请注意@MapsId上的FeatureAffinities.feature批注。

JPA 2.1规范的第2.4.1节中讨论了派生身份。

10-04 17:55