我使用以下代码将DisseminationArea作为Feature的子cals:
@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")
@Getter
@Setter
private long id;
@ManyToOne
@JoinColumn(name = "subtype_id")
@Getter
@Setter
private FeatureSubtype featureSubtype;
@ManyToOne
@JoinColumn(name = "parent_id")
@Getter
@Setter
private Feature parent;
...
}
不幸的是,这在将实体保存到数据库时会导致异常,因为subtype_id字段被使用了两次.
我可以以某种方式注释它,以便JPA知道它是同一字段吗?
解决方法:
如果区分符列对于InheritanceType.JOINED有意义,则值得讨论.我倾向于在连接策略上忽略它,而仅将其与InheritanceType.SINGLE_TABLE一起使用.
但是,可以映射它而不会出现重复的列错误.
如果您的超类实体具有继承/鉴别符定义,例如:
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "subtype_id", discriminatorType = DiscriminatorType.INTEGER)
您只需将映射设置为只读即可将其调整为不像往常一样更新值:
@Column(name="subtype_id", insertable = false, updatable = false)
protected int subTypeId;
public int getSubTypeId() {
return subTypeId;
}
现在,您可以访问实体的鉴别值.