Tuesday, January 15, 2013

Hibernate Best Practices


1) Annotate methods rather than fields to instruct Hibernate to manipulate variables using their accessors.

e.g.,

@Id
@GeneratedValue
@Column(name="CTRY_ID")
public Integer getId() {
return id;
}


2) The Session object is the main runtime interface between a Java application and Hibernate. It offers create, read and delete operations for instances of mapped entity classes.
Session Factory
A Session is obtained from a SessionFactory which can be obtained from the HibernateUtil helper class shown below. This is a common pattern for Hibernate startup in non-Java EE applications.
public class HibernateUtil {

private static SessionFactory sessionFactory;

static {
try {

sessionFactory =
new AnnotationConfiguration()
.configure()
.buildSessionFactory();

} catch (Throwable e) {
System.err.println("Initial SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

public static void shutdown() {
getSessionFactory().close();
}
}
sessionFactory is a static singleton which is instantiated once during startup. This allows multiple Session objects to be created using a single SessionFactory.


view sourceprint?

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

3)

Always use wrapper types for column types to avoid type cast exceptions, incase of loading  a null value for a column.

No comments:

Post a Comment