Java Persistence API
Hibernate is also JPA compatible. EntityManager is the
JPA equivalent of the native Hibernate Session class.
JPA will be added to level up in the
future.
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.
When HibernateUtil calls the configure() method,
a configuration file named hibernate.cfg.xml is loaded from
the root of the classpath. Here is an example of a hibernate.cfg.xml
file which uses an Oracle 10g database: