HSQL In-memory database hibernate maven config example

Reading Time: < 1 minute

maven dependency

<properties>
        <!-- PROJECT DEPENDENCIES BEGIN -->
        <hsqldb.version>2.3.4</hsqldb.version>
        <!-- PROJECT DEPENDENCIES END -->
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>${hsqldb.version}</version>
        </dependency>
    </dependencies>

hibernate configuration

<?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.archive.autodetection">class,hbm</property>
        <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password">1</property>
        <property name="hibernate.connection.url">jdbc:hsqldb:mem:testdb</property>
        <property name="hibernate.hbm2ddl.auto">create</property>

        <mapping class="de.gameduell.entity.User" />
        <mapping class="de.gameduell.entity.Statistics" />
    </session-factory>
</hibernate-configuration>

Converting in between Blob and StringBuilder

Reading Time: < 1 minute

From StringBuilder to Blob

@Autowired
	private SessionFactory sessionFactory;

//saving the blob field
java.sql.Blob blob = org.hibernate.Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(errorDescs.toString().getBytes());

From Blob to StringBuilder

StringBuilder errorDescs = new StringBuilder();
//error description
				if (order.getBatchErrorDescription() == null){
					errorDescs.append(response.getErrors().getDescription().toString() + ";");
				}
				else{
					try {
						Blob blob = order.getBatchErrorDescription();
                                                 byte[] byteData = blob.getBytes(1, (int) blob.length());
						String data = new String(byteData);
						errorDescs.append(data)
								.append(response.getErrors().getDescription().toString() + ";");
					} catch (SQLException e) {
						LOG.error("error cannot retrieve data for error description column of an order id " + order.getOrderId());
					}
				}

Enabling auto reconnect in mysql hibernate spring

Reading Time: < 1 minute

in your spring config file append the url entry with the below sample

 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${database.driverClassName}" />
        <property name="url" value="${database.url}?characterEncoding=UTF-8&amp;autoReconnect=true"/>
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

Hibernate C3P0 pooling integration

Reading Time: < 1 minute

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Hibernate Settings -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://10.10.100.106:3306/nuspa?autoReconnect=true</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">xxxx</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<property name="hibernate.hbm2ddl.auto">validate</property>
		<property name="show_sql">true</property>

		<!-- C3P0 Pooling settings -->
		<property name="hibernate.c3p0.min_size">7</property>
		<property name="hibernate.c3p0.max_size">53</property>
		<property name="hibernate.c3p0.timeout">100</property>
		<property name="hibernate.c3p0.max_statements">50</property>
		<property name="hibernate.c3p0.idle_test_period">1000</property>
		<property name="hibernate.c3p0.validate">true</property>

		<!-- Mapping Entity classes -->
		<mapping class="com.tr.xxx.entity.Customer" />
		<mapping class="com.xxx.entity.Club" />
		<mapping class="com.tr.xxx.entity.TransactionHistory" />
	</session-factory>
</hibernate-configuration>

HibernateUtil.java

package com.xxx.util;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
	private static SessionFactory sessionFactory;
	private final static Logger logger = Logger.getLogger(HibernateUtil.class);

	static {
		try {
			sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			logger.error("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

}

pom.xml

<properties>
		<hibernate-core.version>4.3.5.Final</hibernate-core.version>

	</properties>

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

DAO.java

private final static Logger logger = Logger.getLogger(AppDAOImpl.class);
	final StringBuilder query = new StringBuilder();

	@Override
	public List<Club> getAllClubs() {
		logger.info("fetching all clubs from database");
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		List<Club> clubs = new ArrayList<>();
		try {
			clubs = session.createQuery("from Club").list();
			transaction.commit();
		} catch (HibernateException e) {
			logger.error("Exception in getting all clubs: " + e);
			transaction.rollback();
		}
		return clubs;
	}

Switching Between Hibernate’s and Spring’s Transaction

Reading Time: < 1 minute

Uncomment the below lines to hand the activation down to Spring

pom.xml

<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.tugrulaslan</groupId>
    <artifactId>WebApp</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>BlogWebApp Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project-java.version>1.7</project-java.version>
        <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
        <junit.version>4.11</junit.version>
        <mysql-connector.version>5.1.34</mysql-connector.version>
        <hibernate.version>4.3.8.Final</hibernate.version>
        <javax-persistance-api.version>1.0.2</javax-persistance-api.version>
        <spring.version>4.0.6.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>BlogWebApp</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${project-java.version}</source>
                    <target>${project-java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:property-placeholder location="classpath:hibernate.properties"/>

    <!-- Hibernate connection configuration -->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${orm.connection.driver_class}"/>
        <property name="url" value="${orm.connection.url}"/>
        <property name="username" value="${orm.connection.username}"/>
        <property name="password" value="${orm.connection.password}"/>
    </bean>

    <!-- Hibernate configuration settings -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.tugrulaslan.entity"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${orm.dialect}</prop>
                <prop key="hibernate.show_sql">${orm.show_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${orm.hbm2ddl.auto}</prop>
              <!-- Enabling this will trade transaction management with Hibernate--> 
                <prop key="current_session_context_class">thread</prop>
            </props>
        </property>
    </bean>

    <!-- Spring Transaction Management
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/> -->

    <context:component-scan base-package="com.tugrulaslan"/>
</beans>

hibernate.properties

orm.connection.driver_class = com.mysql.jdbc.Driver
orm.connection.url = jdbc:mysql://localhost:3306/app
orm.connection.username = root
orm.connection.password = root
orm.dialect = org.hibernate.dialect.MySQLDialect
orm.show_sql = true
orm.hbm2ddl.auto = create

DAO

public interface AppDAO {
 public void saveObject(Object object);
}

DAOImpl

@Repository
public class AppDAOImpl implements AppDAO {

    @Autowired
    private SessionFactory sessionFactory;
@Override
    public void saveObject(Object object) {
        
        //Spring's session transaction management use
        //sessionFactory.getCurrentSession().saveOrUpdate(object);
        
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            session.saveOrUpdate(object);
            transaction.commit();
        } catch (HibernateException e) {
            System.err.println(e);
            transaction.rollback();
        } finally {
            session.close();
        }
    }

Service

public interface AppService {
void saveObject(Object object);
}

ServiceImpl

@Service
public class AppServiceImpl implements AppService {
@Override
    //@Transactional
    public void saveObject(Object object) {
        appDAO.saveObject(object);
    }
}