JPA 2.0 improved considerably the support of derived identifiers with the Id
and MapsId
annotations (they should be preferred now) that you can use on XxxToOne
associations. Below one of the example taken from the specification:
2.4.1.3 Examples of Derived Identities
...
Example 4:
The parent entity has a simple primary key:
@Entity public class Person { @Id String ssn; ... }
Case (a): The dependent entity has a single primary key attribute which is mapped by the relationship attribute. The primary key of
MedicalHistory
is of typeString
.@Entity public class MedicalHistory { // default join column name is overridden @Id @OneToOne @JoinColumn(name="FK") Person patient; ... }
Sample query:
SELECT m FROM MedicalHistory m WHERE m.patient.ssn = '123-45-6789'
Case (b): The dependent entity has a single primary key attribute corresponding to the relationship attribute. The primary key attribute is of the same basic type as the primary key of the parent entity. The
MapsId
annotation applied to the relationship attribute indicates that the primary key is mapped by the relationship attribute.@Entity public class MedicalHistory { @Id String id; // overriding not allowed ... // default join column name is overridden @MapsId @JoinColumn(name="FK") @OneToOne Person patient; ... }
Sample query:
SELECT m FROM MedicalHistory m WHERE m.patient.ssn = '123-45-6789'
I think that the MapsId
might be what you're looking for.
Follow-up: Instead of this:
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "prs_pty_id", nullable = false)
@MapsId
private Long prsPtyId;
@Column(name = "name", length = 255)
private String name;
@Column(name = "cellphone", length = 55)
private String cellphone;
@Column(name = "officephone", length = 55)
private String officephone;
@JoinColumn(name = "prs_pty_id", referencedColumnName = "pty_id", nullable = false, insertable = false, updatable = false)
@OneToOne(optional = false)
private Party party;
...
}
Try this:
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "prs_pty_id", nullable = false)
private Long prsPtyId;
@Column(name = "name", length = 255)
private String name;
@Column(name = "cellphone", length = 55)
private String cellphone;
@Column(name = "officephone", length = 55)
private String officephone;
@MapsId
@JoinColumn(name = "prs_pty_id", referencedColumnName = "pty_id")
@OneToOne
private Party party;
...
}
References
- JPA 2.0 specification
- Section 2.4.1 "Primary Keys Corresponding to Derived Identities"
- Section 2.4.1.1 "Specification of Derived Identities"
- Section 2.4.1.2 "Mapping of Derived Identities"
- Section 2.4.1.3 "Examples of Derived Identities"
- JPA Wikibook