I have the following situation:
(source: kawoolutions.com)
JPA 2.0 映射 (仅考虑 Zip 和 ZipId 类可能就足够了,因为这似乎是错误的来源):
@Entity
@Table(name = "GeoAreas")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "discriminator", discriminatorType = DiscriminatorType.STRING)
public abstract class GeoArea implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
protected Integer id;
@Column(name = "name")
protected String name;
...
}
@Entity
@Table(name = "Countries")
@DiscriminatorValue(value = "country")
public class Country extends GeoArea
{
@Column(name = "iso_code")
private String isoCode;
@Column(name = "iso_nbr")
private String isoNbr;
@Column(name = "dial_code")
private Integer dialCode = null;
...
}
@Entity
@Table(name = "Zips")
@IdClass(value = ZipId.class)
public class Zip implements Serializable
{
@Id
@Column(name = "code")
private String code;
@Id
@ManyToOne
@JoinColumn(name = "country_code", referencedColumnName = "iso_code")
private Country country = null;
...
}
public class ZipId implements Serializable
{
private String country;
private String code;
...
}
非常简单的设计:
国家是一个地理区域,它从根类继承 ID。邮政编码在其所在国家/地区是唯一的,因此它结合了 ISO 代码和实际邮政编码作为 PK。因此,Zips 引用了 Country.iso_code,它有一个替代的唯一的、非空的键(参考非主要关键栏!)。 Zip.country 关联获得一个 @Id 注释,其变量名称与其 ID 类 ZipId 中的变量名称相同。
但是我从 Eclipse 中收到此错误消息(也使用 JBoss Tools):
验证消息:
“与 ID 类属性国家/地区匹配的属性没有正确的类型 java.lang.String”
- 为什么这是错误的JPA 2.0语法(参见 Zip.country 上的 @Id 注释)?我不认为是这样。毕竟Zip.country和ZipId.country的类型can't对于 JPA 2 来说是相同的,因为 @ManyToOne 上的 @Id 注释和 PK 是一个简单的整数,它成为 ID 类对应项。有人可以检查/确认吗?
- 这可能是 JBoss Tools 中的一个错误吗? (哪个软件组件报告了上述错误?将 3 个表和实体类放入新的 JavaSE 项目时,没有显示确切代码的错误...)
回答自己的问题...
我对引用建模的方式是使用字符串,因为 FK 指向国家表中的 iso_code 列,该列是 CHAR(2),所以基本上我的映射是正确的。然而,问题是 JPA 2.0 除了引用之外不允许任何其他内容主键列。这就是 Eclipse Dali JPA 验证器所显示的内容。
摘自 Keith/Schincariol 的“Pro JPA 2.0”,第 283 页顶部,“派生标识符的基本规则”(规则 #6):“如果实体中的 id 属性是关系,则实体中匹配属性的类型id 类与关系中目标实体的主键类型具有相同类型(无论主键类型是简单类型、id 类还是嵌入 id 类)。”
个人附录:
我不同意 JPA 2.0 有此限制。 JPA 1.0 映射允许引用非 PK 列。请注意,使用 JPA 1.0 映射并不是我想要的。我宁愿对 JPA 2.0 施加此限制的原因感兴趣。 JPA 2.0 绝对是有限制的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)