Hibernate – SQL Server – Exercise – 01

Background

Wanted to share source code for a sample helloDB Script that I am trying to use as I self teach Hibernate.

Outline

  1. Database File
    • DDL
      • Table
        • dbo.Country
  2. Java Source File
    • helloDB.java
  3. Hibernate Configuration File
    • SQLServerSavila.cfg.xml
  4. Entity
    • Country
      • Country.java ( POJO File )
      • Country.hbm.xml ( XML )

Source Code

Database

DDL

Table

Country
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

USE [sakila]
GO

/*
    drop table [dbo].[country];
*/

/*
    truncate table [dbo].[country];
*/

/*
    select *
    from [dbo].[country];
*/
IF NOT EXISTS
(
    SELECT *
    FROM sys.objects
    WHERE object_id = OBJECT_ID(N'[dbo].[country]')
    AND type in (N'U')
)
BEGIN

    CREATE TABLE [dbo].[country]
    (
        [country_id] [smallint] NOT NULL,
        [country] [varchar](50) NOT NULL,
        [last_update] [datetime] NULL

        , constraint [dbo.PK_Country]
          primary key
        (
            [country_id]
        )
    )
    ON [PRIMARY]

END
GO

Source Code

helloDB.java

package sakila;

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

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

public class helloDB
{

	Configuration objConfiguration = null;

	static String CONFIGURATION_FILE_SQLSERVER = "SQLServerSakila.cfg.xml";

	SessionFactory factoryMSSQL = null;

	static String CHAR_TAB = "\t";

	public static void main(String[] args)
	{

		// TODO Auto-generated method stub
		run();

	}

	public static void run()
	{

			helloDB objHelloDB = null;

			objHelloDB = new helloDB();

			try
			{
				objHelloDB.dbWork();
			}
			catch (Exception ex)
			{

				System.out.println(ex.getMessage());

			}

			objHelloDB =null;

	}

    private Session getDBSession()
    {
    	Session session = null;

    	Configuration cfg= new Configuration();

    	cfg.configure(CONFIGURATION_FILE_SQLSERVER);

    	factoryMSSQL
			= cfg.buildSessionFactory();

    	session = factoryMSSQL.openSession(); 

    	//session = factoryMSSQL.getCurrentSession(); 

    	return session;

    }

    void dbWork()
	//throws Exception
    {

    	try
    	{

    		Session session = null;

    		session = getDBSession();

	    	entityList(session);

	    	countryAddList(session);

	    	countryList(session);

	    	session.close();

	    	factoryMSSQL.close();

    	}
		catch (Exception ex)
		{

			System.out.println(ex.getMessage());

			System.err.println("Failed to create sessionFactory object." + ex);

			throw new ExceptionInInitializerError(ex);
		}

    }

    // list all objects
    private void countryList(Session session)
    {

    	List lists;
    	Country       objCountry;

    	String strLog;

		System.out.println("List Countries");

		System.out.println("==============");

    	lists = session.createQuery("from Country").list(); 

    	System.out.println(lists.size()); 

    	for (int i = 0; i < lists.size(); i++)
    	{ 

			objCountry = lists.get(i);

			strLog = CHAR_TAB
						+ objCountry.getCountry()
						+ " "
						+ "("
						+ objCountry.getCountryID()
						+ ")";

			System.out.println(strLog);

    	}	

    }

    private void countryAddList
    (
		Session session
	)
	throws Exception
    {

    	countryAdd(session, 1, "United States of America");
    	countryAdd(session, 33, "France");
    	countryAdd(session, 44, "United Kingdom");
    	countryAdd(session, 55, "Brazil");
    	countryAdd(session, 61, "Australia");

    }

    private void countryAdd
    (
		  Session session
		, int countryID
		, String country
	)
	throws Exception
    {
        try
        {

        	Transaction transaction = session.getTransaction();

            transaction.begin();

            Country objCountry = new Country();

            objCountry.setCountryID(countryID);
            objCountry.setCountry(country);
            objCountry.settsUpdate(new Timestamp(Calendar.getInstance().getTime().getTime()));

            session.persist(objCountry);

            transaction.commit();

        }

    	catch (Exception ex)
    	{

			System.err.println("Failed to Add country " + country);

			System.out.println(ex.getMessage());

            if (session.getTransaction().isActive())
            {
                session.getTransaction().rollback();
            }

        }

	}

    private void entityList
    (
		  Session session
	)
	//throws Exception
    { 

    	String strEntity;
    	int iNumberofElements;
    	Set objEntityTypeList;

    	try
        {

            objEntityTypeList = session.getMetamodel().getEntities();

            iNumberofElements = objEntityTypeList.size();

        	System.out.println("Retrieve entities ...."); 

        	System.out.println(CHAR_TAB + "Number of elements is " + iNumberofElements); 

        	Transaction transaction = session.getTransaction();

            transaction.begin();

            for (javax.persistence.metamodel.EntityType objEntityType:  session.getMetamodel().getEntities())
            {

            	strEntity = objEntityType.toString();

            	System.out.println(CHAR_TAB + CHAR_TAB + "entity name "+strEntity); 

            }

        	System.out.println("Entities Retrieved"); 

            transaction.commit();

        }

    	catch (Exception ex)
    	{

    		System.out.println(ex.getMessage()); 

            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }

            //throw ex;
        }

	}

}

Hibernate Configuration File

SQLServerSavila.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.dialect">org.hibernate.dialect.SQLServerDialect</property>

  <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>

  <property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=sakila;</property>

  <property name="hibernate.connection.username">sakila</property>

  <property name="hibernate.connection.password">VecRadrI3h</property>

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

  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache  -->
  <property 
  	name="hibernate.cache.use_second_level_cache"> 
  	false
  </property>

  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
  
  <!-- Drop and re-create the database schema on startup -->
  <!-- validate schema on startup -->
 
  <property name="hbm2ddl.auto">validate</property>
  
  <property name="hibernate.default_schema">dbo</property>

 
  <mapping 
  	resource="sakila/Country.hbm.xml"
  	/>
 
  <!-- 
  	 <mapping class="sakila.Employee"/>
	-->
 
 </session-factory>
</hibernate-configuration>

Entity

Country

Country.java ( POJO File )

package sakila;

/*
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
*/

import java.sql.Timestamp;

public class Country
{

	private int CountryID;
	private String Country;
	private Timestamp tsUpdate;

	public Country()
	{

	}

	public Timestamp gettsUpdate()
	{
		return tsUpdate;
	}

	public void settsUpdate(Timestamp tsUpdate)
	{
		this.tsUpdate = tsUpdate;
	}

	public int getCountryID()
	{
		return CountryID;
	}

	public void setCountryID(int countryID)
	{
		CountryID = countryID;
	}

	public String getCountry()
	{
		return Country;
	}

	public void setCountry(String country)
	{
		Country = country;
	}

}

Country.hbm.xml ( HBM.XML File )

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

 <class 
 	name="sakila.Country" 
 	schema="dbo" 
 	table="country"
>


  <id 
  		column="country_id" 
  		name="CountryID" 
  		type="short"
  		/>

  <property 
  		column="country" 
  		generated="never" 
  		lazy="false"
   		name="Country" 
   		type="string"
   		/>
   
  <property 
  		column="last_update" 
  		generated="never" 
  		lazy="false"
   		name="tsUpdate" 
   		type="timestamp"
   		/>
   		
 </class>
</hibernate-mapping>

Source Code Control

GitHub

DanielAdeniji/javaHibernateSQLServerSakila
Link

 

Leave a Reply

Please log in using one of these methods to post your comment:

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