/java/

How to start play with Hibernate.

2015-03-10 01:13:11

In this post you will learn how to establish simple project with hibernate, and how to use two approach to work with entities. Annotation and Xml approach.

First things first

First you have to create new project & configure maven.

<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>

<project http:="" maven-4.0.0.xsd&quot;="" maven.apache.org="" xmlns='"http://maven.apache.org/POM/4.0.0"' xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance"' xsd="" xsi:schemalocation='"http://maven.apache.org/POM/4.0.0'>
<modelversion>4.0.0</modelversion>
<groupid>pl.btbw</groupid>
<artifactid>hibernate-test</artifactid>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupid>org.hibernate</groupid>
<artifactid>hibernate-core</artifactid>
<version>4.2.3.Final</version>
</dependency>
<dependency>
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
<version>5.1.25</version>
</dependency>
</dependencies>
<build>
<pluginmanagement>
<plugins>
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-compiler-plugin</artifactid>
<configuration>
<source/>1.7
                        <target>1.7</target>
</configuration>
</plugin>
</plugins>
</pluginmanagement>
</build>
</project>

Now it is time to configure db connection. I assume that you have installed MySQL. If so, please create new db test with user & password test / test

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `total` int(11) NOT NULL DEFAULT '0',
  `goal` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;

Db configuration

When you have it, you can create simple Util to start work with Hibernate.

HibernateUtil

package pl.btbw;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration().configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (HibernateException ex) {
            System.out.println("ah some problem");
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

Ok time for entities.

Entity for xml approach

package pl.btbw.entity;

public class UserXmlEntity {

    private int id;
    private String name;
    private int total;
    private int goal;

    public UserXmlEntity() {
    }

    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 int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getGoal() {
        return goal;
    }

    public void setGoal(int goal) {
        this.goal = goal;
    }
}

Ok, it looks nice & clean but with this approach we have big disadvantage. We have to use xml to inform hibernate how to mapp obj to db table

user.hbm.xml

<?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
<!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD//EN&quot;
        &quot;http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd&quot;>

<!-- Hibernate Mapping Files -->

<hibernate-mapping>
<class name='"pl.btbw.entity.UserXmlEntity"' table='"user"'>
<meta attribute='"class-description"'/>
            This class contains the employee detail.


        <id column='"id"' name='"id"' type='"java.lang.Integer"'>
<generator class='"identity"/'>
</generator></id>
<property column='"name"' name='"name"' type='"java.lang.String"/'>
<property column='"total"' name='"total"' type='"java.lang.Integer"/'>
<property column='"goal"' name='"goal"' type='"java.lang.Integer"/'>
</property></property></property></class>
</hibernate-mapping>

This works, but this is (for me) ugly as f*, that is why, it is better to use @Annotation

Entity witch @Anotation

package pl.btbw.entity;

import javax.persistence.*;

@Entity
@Table(name = "user")
public class UserAnnotationEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "total")
    private int total;

    @Column(name = "goal")
    private int goal;

    public UserAnnotationEntity() {
    }

    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 int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getGoal() {
        return goal;
    }

    public void setGoal(int goal) {
        this.goal = goal;
    }
}

OK - Great! You will say, but how to test it.

Simple class to test what we have already done.

package pl.btbw;

import org.hibernate.Session;
import pl.btbw.entity.UserAnnotationEntity;
import pl.btbw.entity.UserXmlEntity;

public class Program {

    public static void main(String[] args0) {

        Session session = HibernateUtil.getSessionFactory().openSession();

        session.beginTransaction();

        UserXmlEntity userXml = new UserXmlEntity();
        userXml.setName("michal.xml");
        session.save(userXml);

        UserAnnotationEntity userAnnotation = new UserAnnotationEntity();
        userAnnotation.setName("michal.ano");
        session.save(userAnnotation);

        session.getTransaction().commit();

        session.close();
        HibernateUtil.getSessionFactory().close();

        System.out.println("Hello world");
    }

}

Everything on Github