I want to have a dependent object share the primary key of its parent.
I.E with tables
Table Parent
int PARENT_ID // primary key
String NAME
Table Child
int PARENT_ID // primary key, same as parent's primary key
String NAME
I read somewhere that hibernate allows the @Id annotation with a @OneToOne annotation (Is this only with a newer version of hibernate? I am running 3.2.4.sp1 (comes with jboss 4.2.3.))
So I have the following two entities:
Code:
@Entity
@Table(name = "PARENT")
})
public class Parent implements java.io.Serializable {
private long parentId;
private String name;
private Child child;
public Parent() {
}
@Id
@Column(name = "PARENT_ID", unique = true, nullable = false, scale = 0)
@GeneratedValue( strategy=GenerationType.SEQUENCE, generator="GS_PARENT_GEN" )
@SequenceGenerator( name="GS_PARENT_GEN", sequenceName="GS_PARENT", allocationSize=1 )
public long getParentId() {
return this.parentId;
}
public void setParentId(long parentId) {
this.parentId= parentId;
}
@OneToOne(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
public Child getChild() {
return this.child;
}
public void setChild(Child child) {
this.child = child;
}
@Column(name="NAME", nullable=false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
Code:
@Entity
@Table(name="CHILD")
public class Child {
private Parent parent;
private String name;
public Child() {
}
@Id
@OneToOne(fetch = FetchType.LAZY, mappedBy = "child")
@PrimaryKeyJoinColumn(name = "PARENT_ID")
public Parent getParent() {
return this.parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
@Column(name="NAME", nullable=false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
But I get the following error from hibernate:
Code:
org.hibernate.AnnotationException: Referenced property not a (One|Many)ToOne: com.test.entities.Child.parent in mappedBy of com.test.Parent.child
Any ideas? I this a hibernate problem (i.e. I need a newer version) or is there a flaw in the code?