Java examples on org.hibernate
- How do I create Hibernate's SessionFactory?
- How do I limit the Hibernate query result?
- How do I use Hibernate's Restriction.in criterion?
- How do I retrieve a list of Hibernate's persistent objects?
- How do I retrieve object from database in Hibernate?
- How do I delete persistent object in Hibernate?
- How do I store object in Hibernate?
- How do I use min, max, avg and sum Projections?
- How do I set the fetch mode for Criteria association?
- How do I add Restrictions to the Criteria object?
- How do I select a single record using Criteria?
- How do I count the total records using Projections?
- How do I create a pagination using Criteria?
- How do I order the Criteria query resultset?
- How do I create a Criteria object?
How do I create Hibernate's SessionFactory?
When creating an application the use Hibernate to manage our application persistence object we'll need a SessionFactory. This factory creates or open a session to talk to a database.
To create a SessionFactory we can define the configuration in hibernate.properties, hibernate.cfg.xml or create it programatically. In this example we'll use the hibernate.cfg.xml configuration file, which is mostly use when creating Hibernate application.
Below is our session configuration files.
Now we have the configuration file done, let's create a helper class that will configure and build the SessionFactory object. This helper will be used in other Hibernate example in this site.
package org.kodejava.example.hibernate.app;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SessionFactoryHelper {
private static final SessionFactory sessionFactory;
static {
try {
//
// Build a SessionFactory object from session-factory configuration
// defined in the hibernate.cfg.xml file. In this file we register
// the JDBC connection information, connection pool, the hibernate
// dialect that we used and the mapping to our hbm.xml file for each
// Pojo (Plain Old Java Object).
//
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable e) {
System.err.println("Error in creating SessionFactory object."
+ e.getMessage());
throw new ExceptionInInitializerError(e);
}
}
/**
* A static method for other application to get SessionFactory object
* initialized in this helper class.
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}