Book Image

Mastering Hibernate

Book Image

Mastering Hibernate

Overview of this book

Hibernate has been so successful since its inception that it even influenced the Java Enterprise Edition specification in that the Java Persistence API was dramatically changed to do it the Hibernate way. Hibernate is the tool that solves the complex problem of Object Relational Mapping. It can be used in both Java Enterprise applications as well as .Net applications. Additionally, it can be used for both SQL and NoSQL data stores. Some developers learn the basics of Hibernate and hit the ground quickly. But when demands go beyond the basics, they take a reactive approach instead of learning the fundamentals and core concepts. However, the secret to success for any good developer is knowing and understanding the tools at your disposal. It’s time to learn about your tool to use it better This book first explores the internals of Hibernate by discussing what occurs inside a Hibernate session and how Entities are managed. Then, we cover core topics such as mapping, querying, caching, and we demonstrate how to use a wide range of very useful annotations. Additionally, you will learn how to create event listeners or interceptors utilizing the improved architecture in the latest version of Hibernate.
Table of Contents (16 chapters)

Quick Hibernate


In this section, we take a glance at a typical Hibernate application and its components. Hibernate is designed to work in a standalone application as well as a Java Enterprise application, such as a Web or EJB application. All topics discussed here are covered in detail throughout this book.

The standalone version of a Hibernate application is comprised of the components that are shown in the following figure:

We, the application developers, create the components that are depicted by the white boxes, namely the data access classes, entity classes, and configuration and mapping. Everything else is provided in form of a JAR or a runtime environment.

The Hibernate session factory is responsible for creating a session when your application requests it. The factory is configured using the configuration files that you provide. Some of the configuration settings are used for JDBC parameters, such as database username, password, and connection URL. Other parameters are used to modify the behavior of a session and the factory.

You may already be familiar with the configuration file that looks like the following:

<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">
            org.postgresql.Driver
        </property>
        <property name="connection.url">
            jdbc:postgresql://localhost:5432/packtdb
        </property>
        <property name="connection.username">user</property>
        <property name="connection.password">pass</property>
        <property name="connection.pool_size">1</property>
        <property name="dialect">
           org.hibernate.dialect.PostgreSQLDialect
        </property>
        <property name="current_session_context_class">
            thread
        </property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>        
    </session-factory>
</hibernate-configuration>

The initialization of the session factory has changed slightly in the newer versions of Hibernate. You now have to use a service registry, as shown here:

private static SessionFactory buildSessionFactory() {
    try {
     // Create the SessionFactory from hibernate.cfg.xml
     // in resources directory
      Configuration configuration = new Configuration()
        .configure()
        .addAnnotatedClass(Person.class);
      StandardServiceRegistryBuilder builder = 
        new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties());
      serviceRegistry = builder.build();
      return configuration
        .buildSessionFactory(serviceRegistry);
    }
    catch (Throwable ex) {
        // do something with the exception
        throw new ExceptionInInitializerError(ex);
    }
}

The data objects are represented by Hibernate entities. A simple Hibernate entity, which uses annotation, is shown here:

@Entity
public class Person {
  @Id
  @GeneratedValue
  private long id;
  private String firstname;
  private String lastname;
  private String ssn;
  private Date birthdate;
  // getters and setters
}

The last component that we have to create is the data access class, which is the service that provides the Create, Read, Update, Delete (CRUD) operations for entities. An example of storing an entity is shown here:

Session session = HibernateUtil.getSessionFactory()
  .getCurrentSession();
Transaction transaction = session.beginTransaction();

try {
 Person person = new Person();
 person.setFirstname("John");
 person.setLastname("Williams");
 person.setBirthdate(randomBirthdate());
 person.setSsn(randomSsn());
  session.save(person);
  transaction.commit();
} catch (Exception e) {
  transaction.rollback();
  e.printStackTrace();
} finally {
  if (session.isOpen())
    session.close();
}

That's it!

The Java Enterprise application doesn't look very different from the standalone version. The difference is mainly in the application stack and where each component resides, as shown in the following diagram:

This example provides a context of what we will discuss in detail throughout this book. Let's begin by taking a closer look at a Hibernate session.