Java Reference
In-Depth Information
Listing 2-1 is a reprint of Listing 1-4 from the previous chapter, which shows a complete
usage of Hibernate from within an application. The parts of this listing that deal with configu-
ration and integration are highlighted.
Listing 2-1.
The Hibernate Approach to Retrieving the POJO
public static List getMessages(int messageId)
throws MessageException
{
SessionFactory sessions =
new Configuration().configure().buildSessionFactory();
Session session = sessions.openSession();
try {
session.beginTransaction();
List list = session.createQuery("from Message").list();
session.getTransaction().commit();
return list;
} catch ( HibernateException e ) {
if ( session.getTransaction() != null )
session.getTransaction().rollback();
log.log(Level.SEVERE, "Could not acquire message", e);
throw new MotdException(
"Failed to retrieve message from the database.",e);
} finally {
session.close();
}
}
As you can see, we called the
configure()
method on the
org.hibernate.cfg.
Configuration
class without any arguments. This tells Hibernate to look in the classpath for
the configuration file. The default name for the configuration file is
hibernate.cfg.xml
—if
you change it, you will need to pass that name explicitly as an argument to the
configure()
method. We discuss the
configure()
method and XML configuration in more detail later in
this chapter.
The
configure()
method returns an instance of
Configuration
, which can be used to
obtain a Hibernate
SessionFactory
instance by calling the
buildSessionFactory()
method,
as follows:
public SessionFactory buildSessionFactory() throws HibernateException
The
SessionFactory
is a heavyweight object, and your application should use one
Hibernate
SessionFactory
object for each discrete database instance that it interacts with.
The
SessionFactory
relies on the Hibernate configuration properties, which we detail in the
next section of this chapter.
After you have obtained the
SessionFactory
, you can retrieve Hibernate
org.hibernate.
Session
objects. While the
SessionFactory
is a heavyweight object, the
Session
objects are
lightweight. You perform your persistence operations using
Session
objects.
Search WWH ::
Custom Search