Wednesday, November 5, 2014

Hibernate basics tutorial

Hibernate is a popular ORM framework that allows to store Java objects in the database.
It is the most popular implementation of JPA.

We already worked with JPA basics before, and now we will create a similar application using Hibernate.

This post is available in Russian.

We will use next technologies:
  • Hibernate 4.3.6
  • MySQL 5.6.14
  • Maven 3.1.1

Create hibernate_basics_tutorial database and artist table with id, name and genre columns.
This table will store information about music artists:
CREATE DATABASE hibernate_basics_tutorial;
USE hibernate_basics_tutorial;

CREATE TABLE artist (
id INT PRIMARY KEY,
name VARCHAR(30),
genre VARCHAR(20)
);

Add needed dependencies into pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>hibernate-basics-tutorial</groupId>
    <artifactId>hibernate-basics-tutorial</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.6.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.33</version>
        </dependency>
    </dependencies>

</project>

Create Artist class with idname and genre properties.
Class that could be used by Hibernate is called an entity.
We should add @Entity annotation to turn Artist class into an entity.
Entities of Artist type will be stored in the table of the same name. e.g. artist.
Entity properties values will be stored in the columns of the same name.
Entity should have a persistence identity, or an identifier. It is a key that uniquely identifies an entity instance and distinguishes it from all other instances of the same entity type. Identifier has @Id annotation. id property can be used as an identifier in Artist class, because it corresponds to the primary key column in artist table:
package com.hibernate.basics.tutorial.domain;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Artist {

    @Id
    private int id;

    private String name;
    private String genre;

    public Artist() {

    }

    public Artist(int id, String name, String genre) {
        this.id = id;
        this.name = name;
        this.genre = genre;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }

    @Override
    public String toString() {
        return "Artist{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", genre='" + genre + '\'' +
                '}';
    }
}

Create ArtistService class that has:
  • session property of Session type that implements API for working with entities. save() method stores a new entity, get() performs entity search, delete() deletes entity and createQuery() allows to execute HQL-queries. You don't have to invoke special Session method to update entity property, just change its value (e.g. with setGenre() method)
  • CRUD methods (Create, Read, Update, Delete) that use Session to create, read, update and delete entities
package com.hibernate.basics.tutorial.service;

import com.hibernate.basics.tutorial.domain.Artist;
import org.hibernate.Query;
import org.hibernate.Session;

import java.util.List;

public class ArtistService {

    private Session session;

    public ArtistService(Session session) {
        this.session = session;
    }

    public Artist createArtist(int id, String name, String genre) {
        Artist artist = new Artist(id, name, genre);
        session.save(artist);
        return artist;
    }

    public void removeArtist(int id) {
        Artist artist = (Artist) session.get(Artist.class, id);

        if (artist != null) {
            session.delete(artist);
        }
    }

    public Artist changeArtistGenre(int id, String genre) {
        Artist artist = (Artist) session.get(Artist.class, id);

        if (artist != null) {
            artist.setGenre(genre);
        }

        return artist;
    }

    public Artist findArtist(int id) {
        return (Artist) session.get(Artist.class, id);
    }

    public List<Artist> findAllArtists() {
        Query query = session.createQuery("SELECT a FROM Artist a");
        return query.list();
    }
}

Session is obtained from SessionFactory object.
SessionFactory settings are set in hibernate.cfg.xml file, that must be located in resources directory.
Create that file, set settings to connect the database and list classes that are used by Session (e.g. Artist):
<?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>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_basics_tutorial</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.username">root</property>
        <mapping class="com.hibernate.basics.tutorial.domain.Artist"/>
    </session-factory>
</hibernate-configuration>

Create HibernateBasicsTutorial class to check that application works.
SessionFactorySession and ArtistService objects are created and after that CRUD methods are invoked in main() method.
Methods that are used to create, update and delete entities must be invoked in transactions to store these changes in the database. beginTransaction() and commit() methods of Transaction object are used to open and close transactions:
package com.hibernate.basics.tutorial;

import com.hibernate.basics.tutorial.domain.Artist;
import com.hibernate.basics.tutorial.service.ArtistService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import java.util.List;

public class HibernateBasicsTutorial {

    public static void main(String[] args) {
        Configuration configuration = new Configuration().configure();
        StandardServiceRegistry serviceRegistry =
                new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.openSession();
        ArtistService service = new ArtistService(session);

        System.out.println("--- Create and persist artist ---");
        Transaction transaction = session.beginTransaction();
        Artist artist = service.createArtist(1, "Franz Ferdinand", "Rock");
        transaction.commit();
        System.out.println(String.format("Persisted: %s\n", artist));

        System.out.println("--- Find artist ---");
        artist = service.findArtist(1);
        System.out.println(String.format("Found: %s\n", artist));

        System.out.println("--- Find all artists ---");
        List<Artist> artists = service.findAllArtists();
        for (Artist foundArtist : artists) {
            System.out.println(String.format("Found: %s\n", foundArtist));
        }

        System.out.println("--- Update artist ---");
        transaction = session.beginTransaction();
        artist = service.changeArtistGenre(1, "Indie Rock");
        transaction.commit();
        System.out.println(String.format("Updated: %s\n", artist));

        System.out.println("--- Remove artist ---");
        transaction = session.beginTransaction();
        service.removeArtist(1);
        transaction.commit();
        artist = service.findArtist(1);
        System.out.println(String.format("Found: %s\n", artist));

        session.close();
        sessionFactory.close();
    }
}

Execute main() method:
--- Create and persist artist ---
Persisted: Artist{id=1, name='Franz Ferdinand', genre='Rock'}

--- Find artist ---
Found: Artist{id=1, name='Franz Ferdinand', genre='Rock'}

--- Find all artists ---
Found: Artist{id=1, name='Franz Ferdinand', genre='Rock'}

--- Update artist ---
Updated: Artist{id=1, name='Franz Ferdinand', genre='Indie Rock'}

--- Remove artist ---
Found: null

All CRUD methods were executed correctly, which means we have successfully used Hibernate during application development.

Folder structure:

























Application source code is available at https://code.google.com/p/hibernate-basics-tutorial/.

Recommended posts:

No comments:

Post a Comment