Reputation: 1092
I have two tables, each used to describe information about an object, but coming from two different systems. As such a given object could exist in one, the other, or both.
service_A
---------------
service_A_pkey UUID NOT NULL PRIMARY KEY,
common_identifier TEXT NOT NULL,
<more columns to store data>
and
service_B
---------------
service_B_pkey UUID NOT NULL PRIMARY KEY,
common_identifier TEXT NOT NULL,
<more columns to store data>
Ideally, I'd like both JPA entities to contain references to each other if they exist so that if I use either repository to lookup an object for the given service, it comes with the "extra" information from the other service without needing to do more lookups by hand. From other examples on the web, I thought something like this would work:
@Entity
@Table(name = "service_A")
public class ServiceAData {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "service_A_pkey")
private UUID pkey;
@Column(name = "common_identifier", nullable = false)
private String commonIdentifier;
@OneToOne(optional = true, mappedBy = "serviceAData")
private ServiceBData serviceBData;
}
@Entity
@Table(name = "service_B")
public class ServiceBData {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "service_B_pkey")
private UUID pkey;
@Column(name = "common_identifier", nullable = false)
private String commonIdentifier;
@OneToOne(optional = true)
@JoinColumn(name = "common_identifier", insertable = false, updatable = false)
private ServiceAData serviceAData;
}
The application starts, but actually looking up a ServiceAData object results in
org.postgresql.util.PSQLException: ERROR: operator does not exist: character varying = uuid
Changing ServiceAData's annotations to be exactly the same as ServiceBData's (ie, no mappedBy attribute on @OneToOne, and adding an @JoinColumn) results in essentially the same problem
Caused by: java.lang.IllegalArgumentException: Invalid UUID string: CCGNG23DG0WQ
at java.util.UUID.fromString(UUID.java:194) ~[na:1.7.0_65]
In either case, its trying to convert text/string common_identifier column to a UUID. Am I missing something simple? Going about this the wrong way? Or is what I am trying to do just not possible? I'm not sure if a "bi-directional one-to-one mapping" is really what I should be googling either heh.
To be clear, I don't want either object to own the other - I simply want looking up either object to be supplemented with the other if it is present.
Thanks for any help!
Upvotes: 5
Views: 5871
Reputation: 771
I am using JPA 2.1 and Hibernate 5.0.1. The following works for me:
Have both mapped object members use the following annotations:
@OneToOne(optional = true)
@JoinColumn(name = "common_identifier", referencedColumnName = "common_identifier", insertable = false, updatable = false)
Have both entities implement Serializable. I'm not sure why this part is necessary, but it seems to be.
Upvotes: 3