Did you know that you can navigate the posts by swiping left and right?

How to configure your spring boot application with hibernate

01 Apr 2016 . category: tech . Comments
#tutorial #spring #hibernate #db

To configure your spring boot project with a sql support by Hibernate the first thing you have to do is download the dependencies:

For gradle:

compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.hsqldb:hsqldb:2.3.3")
compile('mysql:mysql-connector-java:5.1.38')

For maven:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
	<version>1.3.3.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.hsqldb</groupId>
	<artifactId>hsqldb</artifactId>
	<version>2.3.3</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.38</version>
</dependency>

Once we have the dependencies imported in our project, is time to configure our application.properties, this is the file in which we indicated to spring the database, username, driver, etc…

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=yourUsername
spring.datasource.password=yourPassword
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create-drop

# ===============================
# = JPA / HIBERNATE
# ===============================

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).

# Show or not log for each sql query
spring.jpa.show-sql = true

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Voila!!!, simply, right?

Well, another thing you need is a runnable database in your machine, I have installed the last version of mysql, you can download from the mysql official page, there is a free version.

Now you need your model object to store in the database:

package com.myolnir.model;

import javax.persistence.*;

@Entity
@Table(name = "test")
public class RelationalObject {

    @Id
    @GeneratedValue
    private Long id;

    @Column (nullable = false)
    private String name;

    @Column
    private String comments;

    public RelationalObject () {
    }

    public RelationalObject (String name, String comments) {
        this.name = name;
        this.comments = comments;
    }

    public String getName () {
        return name;
    }

    public void setName (String name) {
        this.name = name;
    }

    public String getComments () {
        return comments;
    }

    public void setComments (String comments) {
        this.comments = comments;
    }
}

Lets explain this OBJECT MODEL by steps:

  1. As you can see the class has two annotations, @Entity Hibernate will scan your application packages for any Java objects annotated with this annotation. If it finds any, then it will begin the process of looking through that particular Java object to recreate it as a table in your database. Also has the @Table annotation this indicates to Hibernate that this object belongs to the table (if we don’t indicate the table name which belongs our object hibernate will create a new table if it don’t exists yet with the name of our object in snake case, in this case will be relational_object)
  2. The first attribute has the @Id annotation, it indicates that will be the primary key of the table, also has the @GeneratedValue that indicates that is an autogenerated value.
  3. The remaining attributes has the annotation @Column, that indicates they are columns of our table.
  4. We have also an empty constructor (is required by Hibernate) and a field constructor.

So we can store the object into the database we need a DAO object, something like this:

package com.myolnir.repository;

import com.myolnir.model.RelationalObject;
import org.springframework.data.repository.CrudRepository;

public interface RelationalRepository extends CrudRepository<RelationalObject, Long> {
}

This repository (or DAO if you prefer) we extends from spring data crud repository and we indicates the object which we want to work (RelationalObject) and the tipe of the Id field (Long).

We can call the method save with an instance of our RelationalObject and a new table will be created in our database (if it not exists yet) with one new row with the data of our object.

This is the basic configuration, obviously you can extend it much more, you can nested entities, but for start with a basic application this is enough.

You can see the complete code in my github repository

Enjoy it!!