我有以下关系
如您所见,feature_affinities
的详细信息表具有组合键(feature_id
,zoom
),其中的组成部分是外键,引用了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节中讨论了派生身份。