June 29, 2017

A simple Hibernate Example with Maven, Eclipse and SQLServer..

Go to the command prompt execute the following command to generate Maven compatible Java project named as 'HibernateSLC'
mvn archetype:generate -DgroupId=com.khs.scrutiny -DartifactId=HibernateSLC -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Above command will tell Maven to create a Java project from “maven-archetype-quickstart” template. If you ignore the archetypeArtifactId argument, a list of the templates will be listed for you to choose.

To convert Maven project to support Eclipse IDE, on the command prompt navigate to 'HibernateSLC' and execute below command:
mvn eclipse:eclipse

Now, open Eclipse IDE, go to the File – > Import – > General - > Existing Projects into Workspace – >Choose your project folder location.

Once the project is imported, create a resources folder under 'src/main' folder, '/src/main/resources'. All the Hibernate’s xml files will be kept inside this folder. Maven will treat all files in this folder as resources files, and copy it to class path automatically.
Now we need to define thehibernate,sql server and other dependencies in pom.xml 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.javawebtutor< /groupId >
    < artifactId >HibernateSLC< /artifactId >
    < packaging >jar< /packaging >
    < version >1.0-SNAPSHOT< /version >
    < name >HibernateSLC< /name >
    < url >http://maven.apache.org< /url >
    < dependencies >
        < dependency >
            < groupId >junit< /groupId >
            < artifactId >junit< /artifactId >
            < version >3.8.1< /version >
            < scope >test< /scope >
        < /dependency >
        < dependency >
            < groupId >org.hibernate< /groupId >
            < artifactId >hibernate-core< /artifactId >
            < version >4.3.5.Final< /version >
        < /dependency >
        < dependency >
            < groupId >com.microsoft.sqlserver< /groupId >
            < artifactId >mssql-jdbc< /artifactId >
            < version >6.1.0.jre8< /version >
            < scope >test< /scope >
        < /dependency >
    < /dependencies >
< /project >

Go to the command prompt, navigate to 'HibernateSLC' and run 'mvn eclipse:eclipse' command again. When you execute it, Maven will download all Hibernate and SQL Server libraries automatically and put into Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse '.classpath' for dependency purpose.
After this, we will add hibernate configuration xml in the project. Inside '/src/main/resources' folder, create and sml file with name '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 >
        < !-- Database connection settings -- >
        < property name="hibernate.connection.driver_class" >com.microsoft.sqlserver.jdbc.SQLServerDriver< /property >
        < property name="hibernate.connection.url" >jdbc:sqlserver://192.168.31.192:1433;databaseName=mis< /property >
        < property name="hibernate.connection.username" >mis< /property >
        < property name="hibernate.connection.password" >mis< /property >

        < !-- JDBC connection pool (use the built-in) -- >
        < property name="connection.pool_size" >1< /property >

        < !-- SQL dialect -- >
        < property name="dialect" >org.hibernate.dialect.SQLServer2012Dialect< /property >

        < !-- Disable the second-level cache -- >
        < property name="cache.provider_class" >org.hibernate.cache.internal.NoCacheProvider< /property >

        < !-- Echo all executed SQL to stdout -- >
        < property name="show_sql" >true< /property >

        < !-- Drop and re-create the database schema on startup -- >
        < property name="hbm2ddl.auto" >update< /property >

        < mapping resource="user.hbm.xml"/ >
    < /session-factory >
< /hibernate-configuration >


Create model class (Pojo Class) User.java inside com.khs.scrutiny package.
package com.khs.scrutiny;
import java.util.Date;

public class User {
    private int userId;
    private String username;
    private Date joiningDate;
    //getters and setters
}

We will do mapping for model class by creating 'user.hbm.xml' mapping file in the folder 'src/main/resources'.
< ?xml version='1.0' encoding='UTF-8'? >
< !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.khs.scrutiny.User" table="USER_DTL" >
        < id name="userId" type="int" column="USER_ID" >
            < generator class="assigned"/ >
        < /id >
             < property column="USERNAME" name="username" type="java.lang.String"/ >
            < property column="CREATED_BY" name="createdBy" type="java.lang.String"/ >
            < property column="JOINING_DATE" name="joiningDate" type="java.util.Date"/ >  
    < /class >
< /hibernate-mapping >


Create a HibernateUtil.java class to take care of Hibernate start up and retrieve the session easily.
package com.khs.scrutiny;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

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

    private static SessionFactory buildSessionFactory() {
        try
        {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable e) {
            System.err.println("*****inside HibernateUtil(): SessionFactory creation failed." + e);
            throw new ExceptionInInitializerError(e);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
       getSessionFactory().close();
    }
}


Create Test class to insert data into DB.
package com.khs.scrutiny;
import java.util.Date;
import org.hibernate.Session;

public class Test {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
       
        User user = new User();
        user.setUserId(1);
        user.setUsername("Nelson Schott");
        user.setJoiningDate(new Date());

        session.save(user);
        session.getTransaction().commit();
    }
}


When you run Test.java, it will create a new table USER_DTL and insert data in it.

-K Himaanshu Shuklaa..

No comments:

Post a Comment

RSSChomp Blog Directory