First of all, you need to tell Hibernate some information regarding the database system you intend to use, such as host name, port number, JDBC driver class name, database connection URL… via some kind of configuration. Flexibly, Hibernate provides several ways for supplying database configuration:
-
- via properties file.
- via XML file.
- via JNDI data source.
- Programmatic configuration.
- Setting system properties.
We choose XML configuration file. In Eclipse, create a new XML file undersrc directory with this name: hibernate.cfg.xml. Put some configuration information in this file as following:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/contactdb</property>
<property name="connection.username">root</property>
<property name="connection.password">P@ssw0rd</property>
</session-factory>
</hibernate-configuration>
We specify JDBC class driver name (for MySQL), connection URL (which also specifies host name, port number, and database name), user name and password to connect to the database.
The class org.hibernate.cfg.Configuration is used to load the configuration file:
Configuration conf = new Configuration().configure();
The configure() method will read configuration from hibernate.cfg.xml file under program’s classpath.
There are also some overloaded versions of configure() method which allow you to load configuration file in different ways.
The above configuration is only for necessary information. In addition, Hibernate provides a variety of settings such as connection pooling, transaction, debugging… however we don’t cover all of them in this simple tutorial. Just add this line to the hibernate.cfg.xml file:
<property name="show_sql">true</property>
which tells Hibernate to show all SQL statements to the standard output.
Working with Hibernate session
Hibernate provides its database services via a session. In other words, all database operations are executed under context of a Hibernate session. The session manages mapped objects and offers database’s CRUD (create, read, update, delete) operations. Working with Hibernate’s API involves in working with its Session and Session’s relevant methods.
The following code obtains a new session from a session factory:
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
The Session interface defines a number of methods for executing CRUD operations with mapped objects. The following table lists the most common methods provided by the session:
# | Method name | Return | Description | Issued SQL statement |
1 | beginTransaction() | Transaction | Creates a Transaction object or returns an existing one, for working under context of a transaction. | |
2 | getTransaction() | Transaction | Returns the current transaction. | |
3 | get(Class class, Serializable id) | Object | Loads a persistent instance of the given class with the given id, into the session. | SELECT |
4 | load(Class class, Serializable id) | Object | Does same thing as get()method, but throws anObjectNotFound error if no row with the given id exists. | SELECT |
5 | persist(Object) | void | saves a mapped object as a row in database | INSERT |
6 | save(Object) | Serializable | Does same thing as persist()method, plus returning a generated identifier. | INSERT |
7 | update(Object) | void | Updates a detached instance of the given object and the underlying row in database. | UPDATE |
8 | saveOrUpdate(Object) | void | Saves the given object if it does not exist, otherwise updates it. | INSERT or UPDATE |
9 | delete(Object) | void | Removes a persistent object and the underlying row in database. | DELETE |
10 | close() | void | Ends the current session. | |
11 | flush() | void | Flushes the current session. This method should be called before committing the transaction and closing the session. | |
12 | disconnect() | void | Disconnects the session from current JDBC connection. |
Working with Hibernate transaction
Multiple database operations should be executed inside a transaction in order to protect consistence of data in the database in case of exceptions or errors occurred. The following skeleton code illustrates working with a transaction in Hibernate:
session.beginTransaction();
try {
session.persist(Object);
session.update(Object);
session.delete(Object);
} catch (Exception
ex) {
session.getTransaction().rollback();
}
session.getTransaction().commit();
session.close();