Feb 21 2008

Hibernate with Guice – Part I

Published by at 8:20 PM under Guice,Hibernate,Java



In this Blog you will see how to add Google-Guice functionality to a Hibernate-Application. In Part I i will introduce a simple Hibernate-Application. In Part II you can see how this Application will be transformed for using Guice.

Note:
This was my first attempt working with Guice, so i think there are many points which can be improved.

But first for these peoples who doesn’t know what is Guice, Guice is a new lightweight Java 5 Dependency Injection Framework. It is working with Annotations. You should not compare Guice with Spring. Guice focus is on Dependency Injection, where Spring has become popular in the Java community as an alternative, replacement, or even addition to the Enterprise JavaBean model. Google produced Guice for one of their biggest applications – AdWords!

Download-links to all files are available at the end of this posting. Comments are included in the source-listings.

Prerequisites

You need an installed MySql-Server because this Example needs access to a database. If you don’t have one, you can download a preconfigured Wamp for windows here http://www.wampserver.com/en/index.php and for linux there http://www.apachefriends.org/en/xampp.html

Download these Libraries:
Hibernate Core: http://www.hibernate.org/6.html
Guice: http://google-guice.googlecode.com/files/guice-1.0.zip
MySql Connector/J 5.1 http://www.mysql.de/products/connector/j/

Create the database: hibernateguicetest and execute this Query:

CREATE TABLE `Article` (
`id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(30) NOT NULL ,
`price` DOUBLE NOT NULL
) TYPE = innodb;

CREATE TABLE `Customer` (
`id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(30) NOT NULL ,
`street` VARCHAR(30) NOT NULL ,
`city` VARCHAR(30) NOT NULL ,
`postcode` VARCHAR(30) NOT NULL ,
`phone` VARCHAR(30) NOT NULL
) TYPE = innodb;

CREATE TABLE `Orders` (
`id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`customerId` BIGINT NOT NULL,
`articleId` BIGINT NOT NULL,
`amount` INT NOT NULL ,
`orderDate` DATE NOT NULL ,
`sum` DOUBLE NOT NULL ,
FOREIGN KEY (customerId) REFERENCES Customer(id),
FOREIGN KEY (articleId) REFERENCES Article(id)
) TYPE = innodb;

Your database should now look like that (overview from phpMyAdmin):
Database structure

Part I – A simple Hibernate Application

In this part you will create a simple Hibernate Application. The main interesting part is the class HibernateUtil, which handles creation of SessionFactory, Sessions and Transactions. The class OrdersDAO is used for CRUD-Operations. Look at Method initHibernate(), here is the hard coded access to the STATIC HibernateUtil-methods.

Create a new Project “HibernateConnectionWithoutGuice“, add the Hibernate and MySql -JARs to it and create the following files:

Main.java

package eu.jdevelop.hibernateconnectionwithoutguice;

import eu.jdevelop.hibernateconnectionwithoutguice.dao.impl.*;
import eu.jdevelop.hibernateconnectionwithoutguice.model.*;
import eu.jdevelop.hibernateconnectionwithoutguice.util.HibernateUtil;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Hibernate with Guice - Part I
 *
 * This is a simple Hibernate-Application, showing the "normal"
 * way to use Hibernate. To see Guice in Action, just visit Part II.
 *
 * @author Siegfried Bolz (www.jdevelop.eu)
 */
public class Main {

    private static Log logger = LogFactory.getLog(Main.class);

    public static void main(String[] args) {

        /**
         * Create DAO.
         */
        OrdersDAO dao = new OrdersDAO();


        /**
         * Initialize Hibernate Connection
         */
        dao.initHibernate();


        /**
         * Create new Entities.
         */
        Article article1 = new Article();
        article1.setName("Notebook");
        article1.setPrice(999.00);

        Customer customer1 = new Customer();
        customer1.setCity("Munich");
        customer1.setName("Siegfried Bolz");
        customer1.setPhone("555123123");
        customer1.setPostcode("81241");
        customer1.setStreet("Mainstreet 12");

        Orders order1 = new Orders();
        order1.setAmount(2);
        order1.setOrderDate(new Date());
        order1.setSum(article1.getPrice() * order1.getAmount());
        order1.setArticle(article1);
        order1.setCustomer(customer1);


        /**
         * Write Entities into database.
         */
        dao.makePersistent(order1);


        /**
         * Commit Transaction.
         */
        HibernateUtil.commitTransaction();


        /**
         * get number of orders in database
         */
        logger.info("****** Number of orders in database: " + dao.findAll().size());

    }

} // .EOF



IGenericDAO.java

package eu.jdevelop.hibernateconnectionwithoutguice.dao;

import eu.jdevelop.hibernateconnectionwithoutguice.exceptions.InfrastructureException;

/**
 * Interface of the Generic DAO. Use this to create DAO-Implementations
 * from the models.
 *
 * @author Siegfried Bolz
 */
public interface IGenericDAO<t> {

    public void initHibernate()
        throws ExceptionInInitializerError;

    public void makePersistent(T var)
        throws InfrastructureException;

    public void makePersistentUpdate(T var)
        throws InfrastructureException;

    public void makeTransient(T var)
        throws InfrastructureException;

} // .EOF

OrdersDAO.java

package eu.jdevelop.hibernateconnectionwithoutguice.dao.impl;

import eu.jdevelop.hibernateconnectionwithoutguice.dao.IGenericDAO;
import eu.jdevelop.hibernateconnectionwithoutguice.exceptions.InfrastructureException;
import eu.jdevelop.hibernateconnectionwithoutguice.util.HibernateUtil;
import eu.jdevelop.hibernateconnectionwithoutguice.model.*;
import java.util.Collection;
import org.hibernate.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * DAO for Table "orders".
 *
 * @author Siegfried Bolz
 */
public class OrdersDAO implements IGenericDAO<orders> {

    private Log logger = LogFactory.getLog(OrdersDAO.class);

    /**
     * Initialize Hibernate, setup SessionFactory.
     *
     * @throws java.lang.ExceptionInInitializerError
     */
    public void initHibernate() throws ExceptionInInitializerError {
        HibernateUtil.Configure(true);
        HibernateUtil.beginTransaction();
    }

    public void makePersistent(Orders orders) throws InfrastructureException {
        try {
            HibernateUtil.getSession().save(orders);
        } catch (HibernateException ex) {
            HibernateUtil.rollbackTransaction();
            logger.error("Exception in OrdersDAO.makePersistent().", ex);
            throw new InfrastructureException(ex);
        }

    }

    public void makePersistentUpdate(Orders orders) throws InfrastructureException {
        try {
            HibernateUtil.getSession().update(orders);
        } catch (HibernateException ex) {
            HibernateUtil.rollbackTransaction();
            logger.error("Exception in OrdersDAO.makePersistentUpdate().", ex);
            throw new InfrastructureException(ex);
        }

    }

    public void makeTransient(Orders orders) throws InfrastructureException {
        try {
            HibernateUtil.getSession().delete(orders);
        } catch (HibernateException ex) {
            HibernateUtil.rollbackTransaction();
            logger.error("Exception in OrdersDAO.makeTransient(). Rollback activated.", ex);
            throw new InfrastructureException(ex);
        }
    }

    /**
     * Search for all Orders-Entities in Database.
     *
     * @return
     * @throws eu.jdevelop.hibernateconnectionwithoutguice.exceptions.InfrastructureException
     */
    public Collection findAll() throws InfrastructureException {

        Collection collections;
        try {

            collections = HibernateUtil.getSession().createCriteria(Orders.class).list();
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            logger.error("Exception in OrdersDAO.findAll().", ex);
            throw new InfrastructureException(ex);
        } finally {
            HibernateUtil.closeSession();
        }

        return collections;
    }

} // .EOF



InfrastructureException.java

package eu.jdevelop.hibernateconnectionwithoutguice.exceptions;

/**
 * This exception is used to mark (fatal) failures in infrastructure and system code.
 *
 * @author Siegfried Bolz
 */
public class InfrastructureException extends RuntimeException {

  public InfrastructureException() {
  }

  public InfrastructureException(String message) {
    super(message);
  }

  public InfrastructureException(String message, Throwable cause) {
    super(message, cause);
  }

  public InfrastructureException(Throwable cause) {
    super(cause);
  }

} // .EOF



Article.java

package eu.jdevelop.hibernateconnectionwithoutguice.model;

import java.io.Serializable;

/**
 * Simple Article-Model.
 *
 * @author Siegfried Bolz
 */
public class Article implements Serializable{
    private Long id;
    private String name;
    private double price;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

} // .EOF



Customer.java

package eu.jdevelop.hibernateconnectionwithoutguice.model;

import java.io.Serializable;

/**
 * Simple Customer-Model.
 *
 * @author Siegfried Bolz
 */
public class Customer implements Serializable{
    private Long id;
    private String name;
    private String street;
    private String city;
    private String postcode;
    private String phone;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

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

    public String getPostcode() {
        return postcode;
    }

    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

} // .EOF



Orders.java

package eu.jdevelop.hibernateconnectionwithoutguice.model;

import java.io.Serializable;
import java.util.Date;

/**
 * Simple Orders-Model.
 *
 * @author Siegfried Bolz
 */
public class Orders implements Serializable {

    private Long id;
    private Customer customer;
    private Article article;
    private int amount;
    private Date orderDate;
    private double sum;

    public Long getId() {
        return id;
    }

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

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Article getArticle() {
        return article;
    }

    public void setArticle(Article article) {
        this.article = article;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public Date getOrderDate() {
        return orderDate;
    }

    public void setOrderDate(Date orderDate) {
        this.orderDate = orderDate;
    }

    public double getSum() {
        return sum;
    }

    public void setSum(double sum) {
        this.sum = sum;
    }
} // .EOF


The following three *.hbm.xml -files are in the package: eu.jdevelop.hibernateconnectionwithoutguice.model

Article.hbm.xml

<?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="eu.jdevelop.hibernateconnectionwithoutguice.model.Article" table="article">
    <id name="id" column="id">
      <generator class="native" />
    </id>
    <property name="name" column="name" not-null="true" />
    <property name="price" column="price" not-null="true" />
  </class>
</hibernate-mapping>



Customer.hbm.xml

<?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="eu.jdevelop.hibernateconnectionwithoutguice.model.Customer" table="customer">
    <id name="id" column="id">
      <generator class="native" />
    </id>
    <property name="name" column="name" not-null="true" />
    <property name="street" column="street" not-null="true" />
    <property name="city" column="city" not-null="true" />
    <property name="postcode" column="postcode" not-null="true" />
    <property name="phone" column="phone" not-null="true" />
  </class>
</hibernate-mapping>



Orders.hbm.xml

<?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="eu.jdevelop.hibernateconnectionwithoutguice.model.Orders" table="orders">
    <id name="id" column="id">
      <generator class="native" />
    </id>
    <property name="amount" column="amount" not-null="true" />
    <property name="orderDate" column="orderDate" not-null="true" />
    <property name="sum" column="sum" not-null="true" />
    <many-to-one name="customer" class="eu.jdevelop.hibernateconnectionwithoutguice.model.Customer" column="customerId" cascade="save-update"/>
    <many-to-one name="article" class="eu.jdevelop.hibernateconnectionwithoutguice.model.Article" column="articleId" cascade="save-update"/>
  </class>
</hibernate-mapping>



HibernateUtil.java

package eu.jdevelop.hibernateconnectionwithoutguice.util;

import eu.jdevelop.hibernateconnectionwithoutguice.exceptions.InfrastructureException;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.naming.*;

/**
 * Basic Hibernate helper class, handles SessionFactory, Session and Transaction.
 *
 * Uses a static initializer for the initial SessionFactory creation
 * and holds Session and Transactions in thread local variables. All
 * exceptions are wrapped in an unchecked InfrastructureException.
 *
 * @version 1.2
 * @author Siegfried Bolz (www.jdevelop.eu)
 */

public class HibernateUtil {

        /** Logger. */
	private static Log log = LogFactory.getLog(HibernateUtil.class);

	/** configuration. */
	private static Configuration configuration;

	/** Session Factory */
	private static SessionFactory sessionFactory;

	/** JNDI name of sessionfactory. */
	private static final String JNDI_SESSIONFACTORY = "java:hibernate/HibernateFactory";

	/** If running unit tests set to true. */
	private static boolean offlineMode = true;

	/** threadlocal. */
	private static final ThreadLocal threadSession = new ThreadLocal();

	/** threadlocal. */
	private static final ThreadLocal threadTransaction = new ThreadLocal();

	/** threadlocal. */
	private static final ThreadLocal threadInterceptor = new ThreadLocal();

	/** Interceptor class */
	private static final String INTERCEPTOR_CLASS = "hibernate.util.interceptor_class";


	/**
	 * Create the initial SessionFactory from hibernate.xml.cfg or JNDI).
	 * #### Use this Function to initialize Hibernate! ####
	 *
	 * @param offlineMode true=hibernate.cfg.xml , false=JNDI
	 */
	public static void Configure(boolean offlineMode) {
		log.debug("HibernateUtil.Configure() - Trying to initialize Hibernate.");
		try {
			// Use hibernate.cfg.xml (true) or JNDI (false)
			setOfflineMode(offlineMode);
			sessionFactory = getSessionFactory();

		} catch (Throwable x) {
			// We have to catch Throwable, otherwise we will miss
			// NoClassDefFoundError and other subclasses of Error
			log.error("HibernateUtil.Configure() - Building SessionFactory failed.", x);
			throw new ExceptionInInitializerError(x);
		}
	}


    /**
     * Use hibernate.cfg.xml (true) to create sessionfactory or bound
     * sessionfactory to JNDI (false)
     */
    public static void setOfflineMode(boolean mode)
    {
    	if (mode==true)
    	    log.debug("HibernateUtil.setOfflineMode() - Setting mode to hibernate.cfg.xml .");
    	else
    		log.debug("HibernateUtil.setOfflineMode() - Setting mode to JNDI.");

        offlineMode = mode;
    }


        /**
	 * Returns the SessionFactory used for this static class. If offlineMode has
	 * been set then we use hibernate.cfg.xml to create sessionfactory, if not
	 * then we use sessionfactory bound to JNDI.
	 *
	 * @return SessionFactory
	 */
	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null) {
			if (offlineMode == true) {
				log.debug("HibernateUtil.getSessionFactory() - Using hibernate.cfg.xml to create a SessionFactory");
				try {
					configuration = new Configuration();
					sessionFactory = configuration.configure().buildSessionFactory();
				} catch (HibernateException x) {
					throw new InfrastructureException("HibernateUtil.getSessionFactory() - Error creating SessionFactory with hibernate.cfg.xml .",x);
				}

			} else {
				log.debug("HibernateUtil.getSessionFactory() - Using JDNI to create a SessionFactory");
				try {
					Context ctx = new InitialContext();
					sessionFactory = (SessionFactory) ctx.lookup(JNDI_SESSIONFACTORY);
				} catch (NamingException x) {
					throw new InfrastructureException("HibernateUtil.getSessionFactory() - Error creating JNDI-SessionFactory.",x);
				}
			}
		}

		if (sessionFactory == null) {
			throw new IllegalStateException("HibernateUtil.getSessionFactory() - SessionFactory not available.");
		}
		return sessionFactory;
	}


	/**
	 * Sets the given SessionFactory.
	 *
	 * @param sessionFactory
	 */
	public static void setSessionFactory(SessionFactory sessionFactory) {
		HibernateUtil.sessionFactory = sessionFactory;
	}


        /**
	 * Returns the original Hibernate configuration.
	 *
	 * @return Configuration
	 */
	public static Configuration getConfiguration() {
		return configuration;
	}


        /**
	 * Rebuild the SessionFactory with the static Configuration.
	 *
	 */
	public static void rebuildSessionFactory() throws InfrastructureException {
		log.debug("HibernateUtil.rebuildSessionFactory() - Rebuilding the SessionFactory with the static Configuration.");
		synchronized (sessionFactory) {
			try {
				sessionFactory = getConfiguration().buildSessionFactory();
			} catch (Exception x) {
				throw new InfrastructureException("HibernateUtil.rebuildSessionFactory() - Error rebuilding SessionFactory with the static Configuration",x);
			}
		}
	}


        /**
	 * Rebuild the SessionFactory with the given Hibernate Configuration.
	 *
	 * @param cfg
	 */
	public static void rebuildSessionFactory(Configuration cfg) throws InfrastructureException {
		log.debug("HibernateUtil.rebuildSessionFactory() - Rebuilding the SessionFactory from the given Hibernate Configuration.");
		synchronized (sessionFactory) {
			try {
				if (sessionFactory != null && !sessionFactory.isClosed())
					sessionFactory.close();

				sessionFactory = cfg.buildSessionFactory();
				configuration = cfg;
			} catch (Exception x) {
				throw new InfrastructureException("HibernateUtil.rebuildSessionFactory() - Error rebuilding the SessionFactory with the given Hibernate Configuration",x);
			}
		}
	}


        /**
	 * Destroy this SessionFactory and release all resources (caches, connection
	 * pools, etc).
	 *
	 * @author Siegfried Bolz
	 * @param cfg
	 */
	public static void closeSessionFactory() throws InfrastructureException {
		synchronized (sessionFactory) {
			try {
				log.debug("HibernateUtil.closeSessionFactory() - Destroy the current SessionFactory.");
				sessionFactory.close();
				// Clear static variables
				configuration = null;
				sessionFactory = null;
			} catch (Exception x) {
				throw new InfrastructureException("HibernateUtil.closeSessionFactory() - Error destroying the current SessionFactory",x);
			}
		}
	}


        /**
	 * Retrieves the current Session local to the thread. <p/>
	 *
	 * If no Session is open, opens a new Session for the running thread.
	 *
	 * @return Session
	 */
	public static Session getSession() throws InfrastructureException {
		Session s = (Session) threadSession.get();
		try {
			if (s == null) {
				log.debug("HibernateUtil.getSession() - Opening new Session for this thread.");
				if (getInterceptor() != null) {
					log.debug("HibernateUtil.getSession() - Using interceptor: "+ getInterceptor().getClass());
					s = getSessionFactory().openSession(getInterceptor());
				} else {
					s = getSessionFactory().openSession();
				}
				threadSession.set(s);
			}
		} catch (HibernateException x) {
			throw new InfrastructureException("HibernateUtil.getSession() - Error retrieving/creating a session.",x);
		}
		return s;
	}


        /**
	 * Closes the Session local to the thread.
	 */
	public static void closeSession() throws InfrastructureException {
		try {
			Session s = (Session) threadSession.get();
			threadSession.set(null);
			if (s != null && s.isOpen()) {
				log.debug("HibernateUtil.closeSession() - Closing Session of this thread.");
				s.close();
			}
		} catch (HibernateException x) {
			throw new InfrastructureException("HibernateUtil.closeSession() - Error closing the session.",x);
		}
	}


        /**
	 * Start a new database transaction.
	 */
	public static void beginTransaction() throws InfrastructureException {
		Transaction tx = (Transaction) threadTransaction.get();
		try {
			if (tx == null) {
				log.debug("HibernateUtil.beginTransaction() - Starting new database transaction in this thread.");
				tx = getSession().beginTransaction();
				threadTransaction.set(tx);
			}
		} catch (HibernateException x) {
			throw new InfrastructureException("HibernateUtil.beginTransaction() - Error starting a new database transaction.",x);
		}
	}


        /**
	 * Commit the database transaction.
	 */
	public static void commitTransaction() throws InfrastructureException {
		Transaction tx = (Transaction) threadTransaction.get();
		try {
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
				log.debug("HibernateUtil.commitTransaction() - Committing database transaction of this thread.");
				tx.commit();
			}
			threadTransaction.set(null);
		} catch (HibernateException x) {
			rollbackTransaction();
			throw new InfrastructureException("HibernateUtil.commitTransaction() - Error commiting the database transaction.",x);
		}
	}


        /**
	 * Rollback the database transaction.
	 */
	public static void rollbackTransaction() throws InfrastructureException {
		Transaction tx = (Transaction) threadTransaction.get();
		try {
			threadTransaction.set(null);
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
				log.debug("HibernateUtil.rollbackTransaction() - Tyring to rollback database transaction of this thread.");
				tx.rollback();
			}
		} catch (HibernateException x) {
			throw new InfrastructureException("HibernateUtil.rollbackTransaction() - Error rolling back the database transaction.",x);
		} finally {
			closeSession();
		}
	}


        /**
	 * Reconnects a Hibernate Session to the current Thread.
	 *
	 * @param session The Hibernate Session to be reconnected.
	 */
	public static void reconnect(Session session) throws InfrastructureException {
		log.debug("HibernateUtil.reconnect() - Reconnecting Hibernate Session to the current Thread.");
		try {
			session.reconnect(session.connection());
			threadSession.set(session);
		} catch (HibernateException x) {
			throw new InfrastructureException("HibernateUtil.reconnect() - Error reconnectin to the given session.",x);
		}
	}


        /**
	 * Disconnect and return Session from current Thread.
	 *
	 * @return Session the disconnected Session
	 */
	public static Session disconnectSession() throws InfrastructureException {
		log.debug("HibernateUtil.disconnectSession() - Disconnecting Session from current Thread.");
		Session session = getSession();
		try {
			threadSession.set(null);
			if (session.isConnected() && session.isOpen()) {
				session.disconnect();
			}
		} catch (HibernateException x) {
			throw new InfrastructureException("HibernateUtil.disconnectSession() - Error disconnecting session from current thread.",x);
		}
		return session;
	}


        /**
	 * Register a Hibernate interceptor with the current thread.
	 *
	 * Every Session opened is opened with this interceptor after registration.
	 * Has no effect if the current Session of the thread is already open,
	 * effective on next close()/getSession().
	 */
	public static void registerInterceptor(Interceptor interceptor) {
		threadInterceptor.set(interceptor);
	}


        /**
	 * Get Hibernate interceptor.
	 *
	 * @return Interceptor
	 */
	private static Interceptor getInterceptor() {
		Interceptor interceptor = (Interceptor) threadInterceptor.get();
		return interceptor;
	}


        /**
	 * Resets global interceptor to default state.
	 */
	public static void resetInterceptor() {
		log.debug("HibernateUtil.resetInterceptor() - Resetting global interceptor to configuration setting");
		setInterceptor(configuration, null);
	}


        /**
	 * Either sets the given interceptor on the configuration or looks it up
	 * from configuration if null.
	 */
	private static void setInterceptor(Configuration configuration, Interceptor interceptor) {
		String interceptorName = configuration.getProperty(INTERCEPTOR_CLASS);
		if (interceptor == null && interceptorName != null) {
			try {
				log.debug("HibernateUtil.setInterceptor() - Configuring interceptor.");
				Class interceptorClass = HibernateUtil.class.getClassLoader().loadClass(interceptorName);
				interceptor = (Interceptor) interceptorClass.newInstance();
			} catch (Exception x) {
				throw new RuntimeException("HibernateUtil.setInterceptor() - Error, could not configure interceptor: " + interceptorName, x);
			}
		}
		if (interceptor != null) {
			configuration.setInterceptor(interceptor);
		} else {
			configuration.setInterceptor(EmptyInterceptor.INSTANCE);
		}
	}

} // .EOF



The last two files are located at the root of your source-directory.

hibernate.cfg.xml
Take a closer look at this configuration file, if you experience connection-problems to your database.

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

    <!-- Settings for a local MySQL database. -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/hibernateguicetest</property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <!-- Print SQL to stdout. -->
    <property name="show_sql">true</property>

    <!-- Mapping files. -->
    <mapping resource="eu/jdevelop/hibernateconnectionwithoutguice/model/Article.hbm.xml" />
    <mapping resource="eu/jdevelop/hibernateconnectionwithoutguice/model/Customer.hbm.xml" />
    <mapping resource="eu/jdevelop/hibernateconnectionwithoutguice/model/Orders.hbm.xml" />

  </session-factory>
</hibernate-configuration>



log4j.properties

log4j.rootLogger=INFO, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x -%m%n



The file structure looks now like this (here from NetBeans 6):
Netbeans 6 - File structure without guice


If you build and run the application, one entity with its sub-entities will be added to your database:
First records in database

Take enough time to get an overview of the application-code. If you are ready, then proceed with Part II here


Downloads
NetBeans 6 Project Part I: download
Libaries: download

Not only is testking providing material for 350-001 and VCP-310, but is offering online tutors for 640-802 as well as 70-290 and 70-270 series.

Technorati Tags: , , , ,

5 responses so far

5 Responses to “Hibernate with Guice – Part I”

  1. Rich sagt:

    In case you haven’t heard of it I thought I would mention warp-persist, . It’s a very cool, very easy to use way of integrating Hibernate or other JPA containers into your Guice app.

  2. Hibernate with Guice - Part I | Another Random Developer Blog…

    In this Blog you will see how to add Google Guice functionality to a Hibernate Application In Part I i will introduce a simple Hibernate Application In…

  3. [...] Hibernate with Guice – Part I | Another Random Developer Blog (tags: hibernate guice) This entry was written by bairos, posted on March 24, 2008 at 8:24 pm, filed under delicious-daily. Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL. « links for 2008-03-23 [...]

  4. Update:
    I have reformated the code. There is an error in my wordpress, which cause bad formated code.

  5. Steven sagt:

    @Rich:
    I do not recommend WarpPersist. It encourages poor transaction handling.

Leave a Reply


vier − 2 =