Integrating Hibernate using Maven with Mysql using XML

Introduction:
For Detailed introduction on Hibernate please go through this link

In this tutorial we will cover the basic of hibernate using the below :

  1. Maven for dependency Management
  2. Java 7 
  3. Hibernate 4.3.0
  4. Mysql 5.7.16

Creating project using maven : Open command line and type mvn archetype:generate and choose 

mvn archetype:generate  
    -DgroupId=[your project's group id] 
    -DartifactId=[your project's artifact id]  
    -DarchetypeArtifactId=maven-archetype-quickstart
 

$ mvn archetype:generate  -DgroupId=com.tuturself -DartifactId=hibernatetutorial 
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

convert project to import in eclipse using mvn eclipse:eclipse and import into eclipse File-> Import-> Maven-> Existing Maven Project -> Select your project Folder

Adding Maven Dependency:

<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.tuturself</groupId>
    <artifactId>hibernatetutorial</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>hibernatetutorial</name>
    <url>http://maven.apache.org</url>
    <properties>
        <hibernate-commons-version>4.0.5.Final</hibernate-commons-version>
        <hibernate-core-version>4.3.0.Final</hibernate-core-version>
        <hibernate-entitymanager-version>4.3.0.Final</hibernate-entitymanager-version>
        <c3p0-version>0.9.1.2</c3p0-version>
        <mysql-connector-version>5.1.39</mysql-connector-version>
    </properties>
    <dependencies>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>${hibernate-commons-version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate-core-version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate-entitymanager-version}</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0-version}</version>
        </dependency>


        <!-- MySQL database driver -->

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-version}</version>
        </dependency>

    </dependencies>
</project>

Creating DB Schema and Tables

MySQL script to create a “employee” table.

CREATE TABLE `employees` (
  `emp_no` int(11) NOT NULL,
  `birth_date` date NOT NULL,
  `first_name` varchar(14) NOT NULL,
  `last_name` varchar(16) NOT NULL,
  `gender` enum('M','F') NOT NULL,
  `hire_date` date NOT NULL,
  PRIMARY KEY (`emp_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Creating Java POJO Class

package com.tuturself.hibernate.model;

public class Employee implements java.io.Serializable {

	private static final long serialVersionUID = 1L;
	private long employeeCode;
	private String firstName;
	private String lastName;
	private String address;
	private int age;
	/**
	 * @return the employeeCode
	 */
	public long getEmployeeCode() {
		return employeeCode;
	}
	/**
	 * @param employeeCode
	 *          the employeeCode to set
	 */
	public void setEmployeeCode(long employeeCode) {
		this.employeeCode = employeeCode;
	}
	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}
	/**
	 * @param firstName
	 *          the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}
	/**
	 * @param lastName
	 *          the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}
	/**
	 * @param address
	 *          the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param age
	 *          the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
}


Creating Hibernate Mapping file : Create employee.hbm.xml Under /src/main/resources

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.tuturself.hibernate.model.Employee" table="employees">
<id name="employeeNo" type="long">
    <column name="emp_no" />
    <generator class="assigned" />
</id>
<property name="birthDate" type="java.sql.Date">
    <column name="birth_date" />
</property>
<property name="firstName" type="java.lang.String">
    <column name="first_name" />
</property>
<property name="lastName" type="java.lang.String">
    <column name="last_name" />
</property>
<property name="gender" type="java.lang.String">
    <column name="gender" />
</property>
<property name="hireDate" type="java.sql.Date">
    <column name="hire_date" />
</property>
</class>
</hibernate-mapping>

NOTE: Since this POJO class is a simple class, in more complex application this XML might become more tedious to configure and maintain. so we in order to simplify install eclipse hibernate tool which is under JBOSS tools under eclipse market place.

Create Hibernate Configuration file : Create a Hibernate’s configuration file under src/main/resources/hibernate.cfg.xml

<?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.password">root</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/employees</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <mapping resource="com/tuturself/hibernate/model/employees.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

Creating Util Class

This class will take care to get and close the hibernate session related functionality

package com.tuturself.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/** * * @author masterShifu * */
public class HibernateUtil {
	private static SessionFactory sessionFactory = createSessionFactory();
	private static ServiceRegistry serviceRegistry;
	public static SessionFactory createSessionFactory() {
		Configuration configuration = new Configuration();
		configuration.configure();
	//creating session factory using hibernate.cfg.xml
		serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
				configuration.getProperties()).build();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		return sessionFactory;
	}
	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null)
			createSessionFactory();
		return sessionFactory;
	}
	public static void shutdown() {
		getSessionFactory().close();
	}
}

Running the Code 

In order to test the Hibernate functionality we shall create a main class which will try to save a record in db.

package com.tuturself.hibernate;

import java.sql.Date;
import org.hibernate.Session;
import com.tuturself.hibernate.model.Employee;

public class AppStarter {
	public static void main(String[] args) {
		System.out.println("Hibernate Tutorial Using Maven + Hibernate + MySQL");
		Session session = HibernateUtil.getSessionFactory().openSession();

		session.beginTransaction();
		Employee employee = new Employee();
		employee.setEmployeeNo(1234567865L);
		employee.setFirstName("Donald");
		employee.setLastName("Duck");
		employee.setBirthDate(new Date(new java.util.Date().getTime()));
		employee.setGender("M");
		employee.setHireDate(new Date(new java.util.Date().getTime()));
		session.save(employee);
		session.getTransaction().commit();
	}
}

Output:

Hibernate Tutorial Using Maven + Hibernate + MySQL
Nov 08, 2016 2:25:42 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager 
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Nov 08, 2016 2:25:42 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.0.Final}
Nov 08, 2016 2:25:42 PM org.hibernate.cfg.Environment 
INFO: HHH000206: hibernate.properties not found
Nov 08, 2016 2:25:42 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Nov 08, 2016 2:25:42 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Nov 08, 2016 2:25:42 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Nov 08, 2016 2:25:42 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/tuturself/hibernate/model/employees.hbm.xml
Nov 08, 2016 2:25:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Nov 08, 2016 2:25:42 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Nov 08, 2016 2:25:42 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Nov 08, 2016 2:25:42 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/employees]
Nov 08, 2016 2:25:42 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Nov 08, 2016 2:25:42 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Nov 08, 2016 2:25:42 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Tue Nov 08 14:25:42 IST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Nov 08, 2016 2:25:42 PM org.hibernate.dialect.Dialect 
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Nov 08, 2016 2:25:42 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Nov 08, 2016 2:25:42 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory 
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into employees (birth_date, first_name, last_name, gender, hire_date, emp_no) values (?, ?, ?, ?, ?, ?)

 

core java 12 hibernate 12

FOLLOW US ON LinkedIn



Explore Tutu'rself