Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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.



Sunday, March 7, 2010

Not Writable or Invalid Setter Method Exception :


org.springframework.beans.NotWritablePropertyException: Invalid property 'xxxxxx' of bean class [com.company.springhibernateintegration.classes.AddressDAOImpl]: Bean property 'hibernateTemplate' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

Two reasons for occuring this exception is :
  1. When the property is not specified in the bean and is mentioned in the bean registration in the application-context.xml
  2. When you are trying to insert the 'xxxxx' property into the bean through a STATIC Setter.