Thursday, October 20, 2011

Hibernate - No primary key Table

In Hibernate mapping, It is not possible to create a table without a primary key. If you are using annotations, you definitely need to use @Id in your class. But what happens if there is no primary key in your database table.

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.