Hibernate tutorial: quickstart hibernate 4, mysql (annotation)

This tutorial show you how to make a java application and using hibernate to insert record into mysql database.

Tool and technologies using on this guide:

  • Eclipse kepler
  • Maven
  • Hibernate 4
  • Mysql 5.6

1. Create maven project

In Eclipse IDE,go to File->Project-> Maven Project

eclispemaven-01
Choose simple Create a simple project and Next

eclipsemaven-02
Enter follow information

  • Group Id:com.devjav
  • Artifact Id:hibernate

eclipsemavne-03

2. Dependencies

We add follow dependencies to pom.xml file

<dependencies>
    <!-- Hibernate -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.5.Final</version>
    </dependency>
    <!-- Mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!-- test -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
  </dependencies>

3. Model class

We create model class User and annotation as below code

@Entity(name="users")
public class User implements Serializable {
  /**
   * 
   */
  private static final long serialVersionUID = 7292222119906752946L;
  private Long id;
  private String username;
  private String password;
  private Date crtDate;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public Long getId() {
    return id;
  }

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

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  @Column(name = "create_date")
  public Date getCrtDate() {
    return crtDate;
  }

  public void setCrtDate(Date crtDate) {
    this.crtDate = crtDate;
  }

}

4. Create hibernate configuration file

Create hibernate configuration file hibernate.cfg.xml in folder src/main/resources and put following content into that file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="">
  <property name="hibernate.hbm2ddl.auto">update</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.connection.password">admin</property>
  <property name="hibernate.connection.username">root</property>
  <property name="connection.url">jdbc:mysql://localhost/tutorial?autoReconnect=true</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <mapping class="com.devjav.tutorial.hibernate.entity.User"/>
 </session-factory>
</hibernate-configuration>

*Note: you should install Hibernate Tool for save time when develop Hibernate application. Please check this link to know how to install that

5. Create hibernate Util class

Create HibernateUtil.java to manage Hibernate startup and retrieve Hibernate session

public class HibernateUtil {
  private static SessionFactory sf;

  private synchronized static void init() {
    if (sf == null) {
      try {
        Configuration cfg = new Configuration().configure();
        StandardServiceRegistryBuilder serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(cfg.getProperties());
        sf = cfg.buildSessionFactory(serviceRegistry.build());
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }

  public static Session openSession() {
    init();
    return sf.openSession();
  }

}

6. Application Entry

We create App class to do simple task insert record to database.

public class App {

  /**
   * @param args
   */
  public static void main(String[] args) {
    Session session = null;
    Transaction txn = null;
    try {
      session = HibernateUtil.openSession();
      User user = new User();
      user.setCrtDate(new Date());
      user.setUsername("thinhpt");
      user.setPassword("123456");
      txn = session.beginTransaction();
      session.save(user);
      txn.commit();
    } catch (Exception ex) {
      ex.printStackTrace();
      if (txn != null) {
        txn.rollback();
        txn=null;
      }
    } finally {
      if (session != null) {
        session.close();
        session=null;
      }
      HibernateUtil.release();
    }

  }

}

7. Run application

Run this application and it will insert a record users table

Hibernate: insert into users (create_date, password, username) values (?, ?, ?)

8. Source code

You can download source code by click this link

One thought on “Hibernate tutorial: quickstart hibernate 4, mysql (annotation)”

Leave a Reply