Example – Simple Hibernate Application + maven + mysql

Example – Simple Hibernate Application.

1.) Create the java project – “SimpleHibernateApp

  • New > Java Project > <Project name – SimpleHibernateApp> > next > Finnish.
  • convert to Maven Project – Configure > Convert to Maven Project

2.) Add jar files from maven dependencies in POM.xml

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<!– MySQL database driver –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>

<!– Hibernate framework –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>

<!– Hibernate library dependecy start –>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<!– Hibernate library dependecy end –>

<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
</dependencies>

mven_dependency_3.jpg

  • Diagram for maven dependencies.

3.) Create the Persistent class

  • Set the main source in built path for java –  “src/main/java” and resources – “src/main/resources“.

Create the persistent class – User.java , Right click on src/main/java > New > Class – specify the class with package name (e.g. com.fndong.user) – finish.

package com.fndong.user;

import java.util.HashSet;
import java.util.Set;

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

public class User implements java.io.Serializable {

private Integer userId;
private String password;
private String name;
private String email;

public User() {
}

public User(String password, String name, String email) {
this.password = password;
this.name = name;
this.email = email;
}

 

// Set your Getter and Setter

}

4.) Create the mapping file for Persistent class in  com/main/resources

com.fndong.user.User.hbm.xml

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN
http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd“>
<!– Generated Mar 11, 2016 2:47:24 PM by Hibernate Tools 4.3.1.Final –>
<hibernate-mapping>
<class name=”com.fndong.user.User” table=”user” catalog=”hibernate” optimistic-lock=”version“>

<id name=”userId” type=”java.lang.Integer“>
<column name=”user_id” />
<generator class=”identity” />
</id>
<one-to-one name=”userDetails” class=”com.fndong.user.UserDetails
cascade=”save-update”></one-to-one>

<property name=”password” type=”string“>
<column name=”password” not-null=”true” />
</property>

<property name=”name” type=”string“>
<column name=”name” not-null=”true” />

</property>
<property name=”email” type=”string“>
<column name=”email” not-null=”true” />
</property>
</class>

</hibernate-mapping>

5.) Create the Configuration file – com.fndong.user. hibernate.cfg.xml

  • The configuration file contains all the informations for the database such as jdbc connection_url, mysql_driver_class, username, password, and mapping class for User.java and UserDetail.java .
  • The hbm2ddl.auto property is used to create the table in the database automatically.
  • To create the configuration file, right click on src/main/resources > new > com.fndong.user > file and create your file name – hibernate.cfg.xml.

<!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.password“>P@ssw0rd</property>
<property name=”hibernate.connection.url“>jdbc:mysql://localhost:3306/hibernate</property>
<property name=”hibernate.connection.username“>root</property>
<property name=”hibernate.dialect“>org.hibernate.dialect.MySQLDialect</property>
<property name=”cache.provider_class“>org.hibernate.cache.NoCacheProvider</property>
<property name=”show_sql“>true</property>
<property name=”hbm2ddl.auto“>validate</property>

<mapping class=”com.fndong.user.User“/>
</session-factory>
</hibernate-configuration>

hibernate_1

 

6.) Create the class that retrieve or store the persistent object.

  • Create a simple class – call Retrieve.java inside package “com.fndong.user” for storing the User object to the database.

com.fndong.user.Retrieve.java 

package com.fndong.user;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Retrieve {
public static void main(String[] args) {

//creating configuration object
Configuration cfg=new Configuration();
cfg.configure(“hibernate.cfg.xml“);//populates the data of the configuration file

//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();

//creating session object
Session session=factory.openSession();

//creating transaction object
Transaction trans=session.beginTransaction();

User user =new User();
user.setUserId(1);
user.setName(“Franko“);
user.setEmail(“Frankey“);
user.setPassword(“P@ssw0rd“);

//persisting the object
session.merge(user);

//transaction is committed
trans.commit();
session.close();

System.out.println(“successfully created“);

}
}

7.) My Fully structure Project.

proj_struc_hibernate.jpg

8.) Run the application – Retrive.java ( its a main class) – right click class and run > Java Application.

  • Result:

suucess_1.jpg

8. Some constraint and an error with solution:

  • Error: Exception in thread “main” org.hibernate.PersistentObjectException: detached entity passed to persist: com.fndong.user.User
  • Solution: It seems like persist function causes problem, so some solution to use method .merge() as a insert record.

User user =new User();
user.setUserId(1);
user.setName(“Franko“);
user.setEmail(“Frankey“);
user.setPassword(“P@ssw0rd“);

//persisting the object
session.merge(user);

9.) If You Guys want to Download the Source Code. Click Download button Below:

download

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s