Hibernate MySQL tutorial

Hibernate MySQL tutorial

This tutorial will show to how connect MySQL database using hibernate. We will perform simple insert and select operation to MySQL data base to see the results.

Hibernate MySQL tutorial Tools needed:

  • Eclipse ( We are using eclipse Kepler)
  • Install JBoss tools in eclipse. If you are not sure how to install JBoss in eclipse please user this URL: Install JBoss tools in eclipse
  • MySQL data base (Install MySQL Community Server (GPL) version in your system : MySQL Community Server). We are using version 5.6

Hibernate MySQL tutorial below are steps: 

1. Create table in MySQL data base script:

DROP TABLE address
GO

CREATE TABLE address ( 
	Steet_Name	varchar(50) NULL,
	Location  	varchar(25) NULL,
	City      	varchar(25) NULL,
	Zip       	varchar(25) NULL,
	State     	varchar(25) NULL,
	id        	int(11) NOT NULL DEFAULT '0' 
	)
GO

ALTER TABLE address
	ADD PRIMARY KEY (id)
GO

 

2. Eclipse setup:

  • Open your eclipse
  • Create Maven project name: HibernateMySQLTest
  • By default eclipse kepler creates dynamic maven project of version 2.3. If you try to change version to 2.5 through Right click project –>Properties –> Project Facet will give you an error and if you are getting error then click Window –> Show view –> Other –> General –> Navigator –> Click OK
  • Eclipse will change in Navigator perspective. Click .setting folder — and open file name Open org.eclipse.wst.common.project.facet.core.xml file then make change show below:
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="wst.jsdt.web"/>
  <installed facet="java" version="1.5"/>
  <installed facet="jst.web" version="2.5"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>

 

  • This will change maven dynamic project version 2.5.
  • Now create resources folder inside src/main.
  • Create package com.javahonk and com.javahonk.bean and com.javahonk.util
  • Project structure shown below:

hibernate17

3. Hibernate configuration:

4. Create hibernate configuration file:

  • Create file name hibernate.cfg.xml under src/main/resources folder and copy paste below code (Note: Change your MySQL value accordingly) 
<?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>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">admin</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/JavaHonk</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.default_schema">JavaHonk</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

         <property name="show_sql">true</property>
        <mapping resource="Address.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

5. Add dependency in pom.xml file.

  • Copy paste below pom.xml file to your file:
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javahonk</groupId>
  <artifactId>HibernateMySQLTest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>HibernateMySQLTest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

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

	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate</artifactId>
		<version>3.2.3.ga</version>
	</dependency>            

	<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>

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

	<dependency>
		<groupId>asm</groupId>
		<artifactId>asm</artifactId>
		<version>3.1</version>
	</dependency>

  </dependencies>
  <build>
    <finalName>HibernateMySQLTest</finalName>
  </build>
</project>

 

6. Create mapping file

  • Create mapping file name: Address.hbm.xml inside src/main/resources folder and copy paste below code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Feb 20, 2014 5:21:05 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.javahonk.bean.Address" table="address">
        <id name="id" type="int">
            <column name="id" />
            <generator class="increment" />
        </id>
        <property name="steetName" type="string">
            <column name="Steet_Name" length="50" />
        </property>
        <property name="location" type="string">
            <column name="Location" length="25" />
        </property>
        <property name="city" type="string">
            <column name="City" length="25" />
        </property>
        <property name="zip" type="string">
            <column name="Zip" length="25" />
        </property>
        <property name="state" type="string">
            <column name="State" length="25" />
        </property>
    </class>
</hibernate-mapping>

 

7. Create model class

  • Create model class name: Address.java inside package com.javahonk.bean and copy paste below code:
package com.javahonk.bean;
// default package
// Generated Feb 20, 2014 8:14:58 AM by Hibernate Tools 3.4.0.CR1

/**
 * Address generated by hbm2java
 */
public class Address implements java.io.Serializable {

	private int id;
	private String steetName;
	private String location;
	private String city;
	private String zip;
	private String state;

	public Address() {
	}

	public Address(int id) {
		this.id = id;
	}

	public Address(int id, String steetName, String location, String city,
			String zip, String state) {
		this.id = id;
		this.steetName = steetName;
		this.location = location;
		this.city = city;
		this.zip = zip;
		this.state = state;
	}

	public int getId() {
		return this.id;
	}

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

	public String getSteetName() {
		return this.steetName;
	}

	public void setSteetName(String steetName) {
		this.steetName = steetName;
	}

	public String getLocation() {
		return this.location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getCity() {
		return this.city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getZip() {
		return this.zip;
	}

	public void setZip(String zip) {
		this.zip = zip;
	}

	public String getState() {
		return this.state;
	}

	public void setState(String state) {
		this.state = state;
	}

}

 

8. Create utility class

  • Create util class name HibernateUtil.java inside com.javahonk.util package and copy paste below code:
package com.javahonk.util;

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

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			return new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		// Close caches and connection pools
		getSessionFactory().close();
	}
}

 

9. Create main class

  • Finally create main class which is java main class. We will use this class to insert and select data from table. Create class name InsertData.java inside package com.javahonk and copy paste below code in it:
package com.javahonk;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.javahonk.bean.Address;
import com.javahonk.util.HibernateUtil;

public class InsertData {

	public static void main(String[] args) {		

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

        session.beginTransaction();
        Address address=new Address();
		address.setSteetName("Main St."); 
		address.setLocation("APT 55");
		address.setCity("Edison");
		address.setZip("10038");
		address.setState("NJ");		

        session.save(address);
        session.getTransaction().commit();

        Query query=session.createQuery("FROM Address");
        List list =query.list();
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Address address1 = (Address) iterator.next();
			System.out.println("Stree Name: "+address1.getSteetName()+" Location: "+address1.getLocation()+" City: "+address1.getCity()+" State: "+address1.getState()+" Zip: "+address1.getZip());

		}

	}

}

 

  • Hibernate MySQL tutorial we are all set to run our code. Before run refresh and clean your project. Right click InsertData.java class –> Run As –> Java Application
  • You will on console it inserted data to table name address and select data from the table that also show on console as below:

hibernate18

  • That’s it. Hibernate MySQL tutorial completed

download2 Download project: HibernateMySQLTest

Leave a Reply

Your email address will not be published. Required fields are marked *