Hibernate works as an interface between the java object of our project
and a database (via a external database connector). It provides the functionality to save
the native java objects into the database, generates the tables, writes entities and cares for the relations
between objects. We don't have to write a single line of SQL-Code to interact with the database
although we don't lose any kind of possibilities for interaction.
Install the external packages either from the .jar files or use a project manager for that
We can download the .zip or .tz from here
Then extract all the files in the /lib
folder as well as the hibernateXX.jar
to our projects CLASSPATH
Include the following dependency in our pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-agroal</artifactId>
<version>5.3.14.Final</version>
<type>pom</type>
</dependency>
Depending on your Database, we also have to download the correct Database connector as well.
To allow Hibernate to connect to the database, we have to tell the program how and where to connect.
This is done by the hibernate.cfg.xml
file. Look into hibernate.cfg.xml
to see an example.
One way to bind the object mappings of the java objects to the corresponding database fields,
is to configure the bindings in xml mapping files, that are referenced from the hibernate.cfg.xml
like this:
<mapping resource = "Student.hbm.xml"/>
An example for a mapping file can be found here
The other way of adding the bindings is to use annotations directly in the java code
Reference a external xml file, containing the bindings, in the hibernate.cfg.xml
as described in Object Mappings
Most important tags:
<hibernate-mapping>
is the root tag, surrounding all hibernate mapping definitionsclass
maps a Java Class to a database table. Contains different tags to describe the single columns matching to various attributes<id>
marks the key attribute/column<property>
describes a standard table column's mapping to a Java attribute<set>
defines a relation between multiple tablesgenerator
marks any attribute as autogenerated by the databasemeta
adds additional information, e.g. a table description
Example File
Add the mappings as annotations directly into your Java source code.
Annotations for object attributes:
@Entity
starts a new entity definition@Table
maps a Java Class to a database table@Id
marks the key attribute/column@Column
describes a standard table column's mapping to a Java attribute@GeneratedValue
marks any attribute as autogenerated by the database@OneToMany
/@OneToOne
/@ManyToOne
/@ManyToMany
defines relations between different classes
Example File
As everything in this tutorial is just an overview of the very basic functionality. For more details look into the javadoc of Hibernate
The SessionFactory
works as a factory object to create sessions to the database in our project.
It's thread save and can be used by all threads of the application.
We can create it from a Configuration
object, which contains the information
about the database connection from hibernate.cfg.xml
and the mappings from either then xml-file
or the java Annotations.
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
//Add further attributes to the configuration e.g.: annotated class
configuration.addAnnotatedClass(Student.class);
SessionFactory factory = configuration.buildSessionFactory();
A Session
represents the physical connection to the database. It should be instantiated
each time we need it as it is not thread safe and therefore should not be keep open for too long.
Session session = factory.openSession();
//Interact with the database
session.close();
Transactions are an optional object and not required for a database interaction but most of the databases support this functionality and therefore hibernate supports it as well.
tx = session.beginTransaction();
//Do querys etc.
tx.commit();
tx = session.beginTransaction();
Student me = new Student("Moritz", new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2001"));
int StudentID = (Integer) session.save(me); // Add student element
//session.saveOrUpdate(student); to save if entry does not exist, otherwise update it
Student student = (Student)session.get(Student.class, StudentID); // Get student entry
student.setName("Max");
session.update(student); // Update student entry
session.delete(student); //Delete student entry
tx.commit();
Session methods for CRUD operations:
save()
Saves the given object and returns the database output (in most cases the id)get()
Queries for a key value and returns the result as an object of the given classdelete()
Removes the object's representation in the databaseupdate()
Updates the values in the database with the attributes of the objectsaveOrUpdate()
Either saves the object, if it is not yet saved in the database, or updates an already present representation
For further or more complex queries, hibernates provides a SQL Dialect Hibernate Query Language (HQL) for querying the database. One option is to write it as plain text query, similar to SQL.
String hql = "FROM Student S WHERE S.id > 2 ORDER BY S.birthdate ASC";
Query query = session.createQuery(hql);
List results = query.list();
Another option is to generate a query (now called Criteria) by multiple method calls.
Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.gt("id", 2));
cr.addOrder(Order.asc("birthdate"));
cr.list();
As a third option it is also possible to execute SQL statements. BUT the response is not wrapped into an object.
Query query = session.createSQLQuery("SELECT * FROM Student WHERE id > 2 ORDER BY birthdate ASC");
List<Object[]> rows = query.list();