Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Hibernate

You're reading from   Mastering Hibernate Learn how to correctly utilize the most popular Object-Relational Mapping tool for your Enterprise application

Arrow left icon
Product type Paperback
Published in May 2016
Publisher Packt
ISBN-13 9781782175339
Length 204 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

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:

Quick Hibernate

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:

Quick Hibernate

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image