:::: MENU ::::

Hibernate


Hibernate is a tool that implements the JPA specification to map Java classes with database objects.

Database table

We will use a table in a MySQL type database. After installing XAMPP and in phpMyAdmin we are going to create a database called “mydatabase” and there we will introduce (in the SQL tab) the following code:

mytable.sql

CREATE TABLE `mytable` (
  `myId` int(11) NOT NULL,
  `myString` varchar(32) NOT NULL,
  `myDate` date NOT NULL,
  `myFloat` float(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `mytable`
  ADD PRIMARY KEY (`myId`);

ALTER TABLE `mytable`
  MODIFY `myId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
COMMIT;

Java Class

We will map the table with the following Java class (that we will create later in the project after creating it).

MyTable.java

package com.luisgomezcaballero.data.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "mytable")
public class MyTable {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer myId;
	private String myString;
	private Date myDate;
	private Float myFloat;

	public Integer getMyId() {
		return myId;
	}

	public void setMyId(Integer myId) {
		this.myId = myId;
	}

	public String getMyString() {
		return myString;
	}

	public void setMyString(String myString) {
		this.myString = myString;
	}

	public Date getMyDate() {
		return myDate;
	}

	public void setMyDate(Date myDate) {
		this.myDate = myDate;
	}

	public Float getMyFloat() {
		return myFloat;
	}

	public void setMyFloat(Float myFloat) {
		this.myFloat = myFloat;
	}

}

Creation of a new project

We create a new Maven project, to better manage the dependencies and, then, we create the previous Java class.

Dependencies

Now we open the pom.xml file and introduce this four dependencies:


  <dependencies>
  	<dependency>
  		<groupId>org.hibernate</groupId>
  		<artifactId>hibernate-core</artifactId>
  		<version>5.3.0.Beta2</version>
  	</dependency>
  	<dependency>
  		<groupId>org.hibernate</groupId>
  		<artifactId>hibernate-annotations</artifactId>
  		<version>3.5.6-Final</version>
  	</dependency>
  	<dependency>
  		<groupId>org.slf4j</groupId>
  		<artifactId>slf4j-api</artifactId>
  		<version>1.8.0-beta1</version>
  	</dependency>
  	<dependency>
  		<groupId>org.slf4j</groupId>
  		<artifactId>slf4j-log4j12</artifactId>
  		<version>1.8.0-beta1</version>
  	</dependency>
  </dependencies>

In addition, as we are going to use MySQL, we need the Java connector. We include it too:

  	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>8.0.9-rc</version>
  	</dependency>

We wait until the are downloaded.

Configuration

We are going to configure the project to have a unique session element. To do this we will use a Singleton pattern and an additional class called Util.java. It is important to correctly specify the properties in according to our database configuration. In tihs case we will use a Properties object, but it is more common to use a XML configuration using a file called hibernate.cfg.xml.

Util.java

package com.luisgomezcaballero.data;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import com.luisgomezcaballero.data.entity.MyTable;

public class Util {
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		Configuration configuration = new Configuration();

		configuration.addAnnotatedClass(MyTable.class);
		
		Properties properties = new Properties();
		properties.put("hibernate.connection.username", "root");
		properties.put("hibernate.connection.password", "");
		properties.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
		properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/myDatabase");
		
		configuration.setProperties(properties);
		
		return configuration.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

main() method

We create a class with a main method in where we we create the session, start the transaction, create a MyTable type object, filling its properties, and finally we persist it.

HibernateDemo.java

package com.luisgomezcaballero.data;

import java.util.Date;

import org.hibernate.Session;

import com.luisgomezcaballero.data.entity.MyTable;

public class HibernateDemo {

	public static void main(String[] args) {

		Session session = Util.getSessionFactory().openSession();
		session.getTransaction().begin();

		MyTable myTable = new MyTable();
		myTable.setMyString("test1");
		myTable.setMyDate(new Date());
		myTable.setMyFloat(new Float("1.25"));
		
		session.save(myTable);
		session.getTransaction().commit();
		session.close();
	}

}

Example of use

Right click on HibernateDemo, Run As Java Application. On the console we will see (if there are not any configuration error that will show in red color) the object we created with the values we specified. By opening phpMyAdmin we will see the content of the table, and that our data are introduced correctly.

Repository

This demonstration project can be located at https://github.com/luisgomezcaballero/hibernate-demo.


So, what do you think ?