You can use the referencedColumnName @JoinColumn attribute as indicated here . Therefore, for your example, the mappings should be as follows:
ObjA.java:
package hello; import org.hibernate.annotations.NaturalId; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class ObjA { Long id; String uuid; public ObjA() { } public ObjA(String uuid) { this.uuid = uuid; } @Id @GeneratedValue @Column(name = "obj_a_id", unique = true, nullable = false) Long getId() { return id; } public void setId(Long id) { this.id = id; } @NaturalId(mutable = false) @Column(name = "uuid", unique = true, nullable = false) public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
Association.java:
package hello; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Association { Long id; ObjA main; ObjA sub; public Association() { } public Association(ObjA main, ObjA sub) { this.main = main; this.sub = sub; } @Id @GeneratedValue @Column(name = "association_id", unique = true, nullable = false) Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne @JoinColumn(name = "main_uuid", referencedColumnName = "uuid", nullable = false) public ObjA getMain() { return main; } public void setMain(ObjA main) { this.main = main; } @ManyToOne @JoinColumn(name = "sub_uuid", referencedColumnName = "uuid", nullable = false) public ObjA getSub() { return sub; } public void setSub(ObjA sub) { this.sub = sub; } }
These mappings have been successfully tested to store values ββfrom the uuid column of the obja table in the main_uuid and sub_uuid columns of the association table. This has been tested using org.hibernate.common:hibernate-commons-annotations:4.0.5.Final , org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final , org.hibernate:hibernate-core:4.3.10.Final and org.hibernate:hibernate-entitymanager:4.3.10.Final for PostgreSQL 9.4.4.
source share