There is a workaround for this if your table is having some sort of unique relationship to any other table.
Consider two classes. Parent and a Child.
Parent has a primary key property but Child do not.
@Entity
@Table(name = "ParentTableName")
class Parent{
protected Integer id;
@Id
@Column(name = "PrimaryKeyColumnName", nullable = false)
public Integer getId() {
return id;
}
}
@Entity
@Table(name = "ChildTableName")
class Child{
private Parent parent;
@Id
@OneToOne @JoinColumn(name = "FKColumnNameInChildTable", nullable = false)
public Parent getParent() { return parent; }
public void setParent(Parent parent) { this.parent = parent;
}
}
Here even though, no primary key is specified in the database table, we are informing Hibernate to treat the Foreign Key as the primary key.
But what if you we have a unique relation on multiple columns in the child table?
In that case we can specify @Id annotation to all the relations and specify those relations with @Embeddable annotation.
No comments:
Post a Comment