Spring Hibernate Sybase Integration example

Spring Hibernate Sybase Integration example

Building application from scratch is one of the biggest task in software development and if you got requirement to build application using Spring Hibernate and Sybase database hmmm… challenging but I will make your life little easy to give you some idea about how to get going with this kind of architecture. I will be building application using yes Spring Hibernate and Sybase database and will show how to use @Transactional annotation and handle transaction and in this example we just call and get data using store procedure, native select query and hibernate ORM. Let’s get started:

  • First create table using below script in Sybase database I using version Adaptive Server Enterprise 15.7.:
/***** create table dbo.EquitySwapTest *****/
create table dbo.EquitySwapTest (
  underlierRicCode varchar(20) null,
  underlierSmID int null,
  underlierCusip varchar(20) null,
  underlierAssetType varchar(20) null,
  div_list_id int null,
  eventDate int null
) on 'default'
 partition by roundrobin(
EquitySwapTest_642098297 on 'default')

lock allpages

go
  • Also create store procedure which will make call to above table to get the data and for our example we will call both table and store procedure to get data:
Setuser 'dbo'
go
/***** create procedure dbo.EquitySwapTestProcedure *****/
create procedure dbo.EquitySwapTestProcedure @eventDate int
as
SELECT
newID(1) AS rowKey,underlierRicCode, underlierSmID, underlierCusip, underlierAssetType, div_list_id 
FROM OTC.dbo.EquitySwapTest where eventDate = @eventDate
 go


Setuser
go
  • Insert some dummy data for test:
INSERT INTO OTC.dbo.EquitySwapTest(
   underlierRicCode
  ,underlierSmID
  ,underlierCusip
  ,underlierAssetType
  ,div_list_id
  ,eventDate
) VALUES (
   'underlierRicCode'
  ,12365
  ,'underlierCusip'
  ,'underlierAssetType'
  ,1254
  ,20151028
)
  • Create maven project name: SpringHibernateSysbaseIntegration below is final project structure:

 

  • As you see above I have created separate package for dao, model and application test also kept all properties files in src/main/resources folder and database, queries and context in src/main/config folder separately. As nothing much to explain about it I will give explanation in the file what I am doing:

Spring Hibernate Sybase Integration example

  • pom.xml: Managing project dependencies:
<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javahonk</groupId>
  <artifactId>SpringHibernateSysbaseIntegration</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		
		<apache.commons.lang.version>3.3.2</apache.commons.lang.version>
		<commons.collections.version>3.2.1</commons.collections.version>
		<commons.logging.version>1.2</commons.logging.version>
		<org.apache.log4j.version>2.1</org.apache.log4j.version>
		
		<objenesis.version>2.1</objenesis.version>
		
		<cglib.version>3.2.0-SS</cglib.version>

		<dom4j.version>1.6.1</dom4j.version>
		
		<xercesImpl.version>unknown</xercesImpl.version>

		<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
		
		<org.ow2.asm.version>5.0.3</org.ow2.asm.version>
		
		<org.javassist.version>3.18.1-GA</org.javassist.version>
		
		<org.jboss.logging.version>3.1.3.GA</org.jboss.logging.version>
		
		<org.apache.geronimo.version>1.1.1</org.apache.geronimo.version>
		
		<org.hibernate.core.version>4.3.9.Final</org.hibernate.core.version>
		<org.hibernate.entitymanager.version>4.3.9.Final</org.hibernate.entitymanager.version>
		<org.hibernate.annotations.version>4.0.5.Final</org.hibernate.annotations.version>
		<org.hibernate.jpa.version>1.0.0.Final</org.hibernate.jpa.version>
		
		<junit.version>4.12</junit.version>		
	</properties>

	<dependencies>
	
		<!-- JUNIT -->
		<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

		<!-- Spring -->
		<!-- Core utilities used by other modules. Define this if you use Spring 
			Utility APIs (org.springframework.core.*/org.springframework.util.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Expression Language (depends on spring-core) Define this if you use 
			Spring Expression APIs (org.springframework.expression.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Bean Factory and JavaBeans utilities (depends on spring-core) Define 
			this if you use Spring Bean APIs (org.springframework.beans.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Aspect Oriented Programming (AOP) Framework (depends on spring-core, 
			spring-beans) Define this if you use Spring AOP APIs (org.springframework.aop.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Application Context (depends on spring-core, spring-expression, spring-aop, 
			spring-beans) This is the central artifact for Spring's Dependency Injection 
			Container and is generally always defined -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Various Application Context utilities, including EhCache, JavaMail, 
			Quartz, and Freemarker integration Define this if you need any of these integrations -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- JDBC Data Access Library (depends on spring-core, spring-beans, spring-context, 
			spring-tx) Define this if you use Spring's JdbcTemplate API (org.springframework.jdbc.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA, 
			and iBatis. (depends on spring-core, spring-beans, spring-context, spring-tx) 
			Define this if you need ORM (org.springframework.orm.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Web application development utilities applicable to both Servlet and 
			Portlet Environments (depends on spring-core, spring-beans, spring-context) 
			Define this if you use Spring MVC, or wish to use Struts, JSF, or another 
			web framework with Spring (org.springframework.web.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Support for testing Spring applications with tools such as JUnit and 
			TestNG This artifact is generally always defined with a 'test' scope for 
			the integration testing framework and unit testing stubs -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework.version}</version>
			<scope>test</scope>
		</dependency>
		
		<!-- Spring Aspects -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<!-- Spring Tx -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- dom4j -->
		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>${dom4j.version}</version>
		</dependency>
		
		<!-- xerces -->
		<dependency>
			<groupId>xerces</groupId>
			<artifactId>xercesImpl</artifactId>
			<version>${xercesImpl.version}</version>
		</dependency>
		
		<dependency>
			<groupId>com.tunnelvisionlabs</groupId>
			<artifactId>antlr4</artifactId>
			<version>4.4</version>
			<classifier>complete</classifier>
		</dependency>

		<!-- objenesis -->
		<dependency>
			<groupId>org.objenesis</groupId>
			<artifactId>objenesis</artifactId>
			<version>${objenesis.version}</version>
		</dependency>

		<!-- apache commons -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>${apache.commons.lang.version}</version>
		</dependency>
		
		<!-- commons-io -->		
		<dependency>	
			<groupId>commons-io</groupId>
  		  	<artifactId>commons-io</artifactId>
  		  	<version>2.4</version>
		</dependency>
			
		<!-- commons collections -->
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>${commons.collections.version}</version>
		</dependency>	
		
		<!-- commons logging -->
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>${commons.logging.version}</version>
		</dependency>

		<!-- cglib -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<!--<version>3.1</version> -->
			<version>${cglib.version}</version>
		</dependency>
		
		<!-- jdbc driver -->
		<dependency>
        	<groupId>com.sybase.jdbcx</groupId>
        	<artifactId>jconn4</artifactId>
        	<version>7.07</version>
        </dependency>
        
        <!-- aop alliance -->
		<dependency>
			<groupId>aopalliance</groupId>
			<artifactId>aopalliance</artifactId>
			<version>1.0</version>
		</dependency>
		
		<!-- asm -->
		<dependency>
			<groupId>org.ow2.asm</groupId>
			<artifactId>asm</artifactId>
			<version>${org.ow2.asm.version}</version>
		</dependency>
		
		<!-- hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${org.hibernate.core.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${org.hibernate.entitymanager.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.common</groupId>
			<artifactId>hibernate-commons-annotations</artifactId>
			<version>${org.hibernate.annotations.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.1-api</artifactId>
			<version>${org.hibernate.jpa.version}</version>
		</dependency>
		
		<!-- Log4j -->
        <dependency>
        	<groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${org.apache.log4j.version}</version>
		</dependency>
        
        <dependency>
        	<groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${org.apache.log4j.version}</version>
		</dependency>	
		

	</dependencies>

	
</project>
  • hibernate.properties: This file we are putting all database related information like url, user name, password and hibernate related configuration:
jdbc.driverClassName=com.sybase.jdbc4.jdbc.SybDriver
default_streamed_object_size=5000
default_max_query_size=1000
jdbc.url=jdbc:sybase:Tds:javahonk:12000
jdbc.username=javahonk
jdbc.password=javahonk123

hibernate.dialect=org.hibernate.dialect.SybaseASE157Dialect
hibernate.show_sql=false
hibernate.jdbc.lob.non_contextual_creation=true
c3p0.acquireIncrement=2
c3p0.maxPoolSize=10
c3p0.minPoolSize=1
c3p0.maxIdleTime=1800
  • application.properties: This is where we will keep application related properties mapping.
query_getEquitySwapTestData=getEquitySwapTestData
  • log4j2.xml: For keeping log of the application:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" shutdownHook="disable">

	<Properties>
		<Property name="envrionment.target">DEV</Property>
	</Properties>

	<Properties>
		<Property name="logging.dir">./</Property>
	</Properties>

	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</Console>

		<RollingFile name="RollingFile"
			fileName="./logs/rolling-file.log"	filePattern="${sys:logging.dir}/logs/rolling-file-%d{yyyy-MM-dd}-%i.log">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
			<!-- TODO:Change to time based policy -->
			<Policies>
				<TimeBasedTriggeringPolicy interval="1"	modulate="true" />
				<SizeBasedTriggeringPolicy size="100 MB" />
			</Policies>
			<DefaultRolloverStrategy max="4" />
		</RollingFile>
	</Appenders>

	<Loggers>
		<Root level="info">
			<AppenderRef ref="Console" />
			<!-- <AppenderRef ref="file" /> -->
			<AppenderRef ref="RollingFile" />
		</Root>
	</Loggers>
</Configuration>
  • hibernate-context.xml: Hibernate related configuration where you need to configure datasource, session factory etc…
<?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:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	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-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">	
	
	<context:component-scan base-package="com.javahonk.dao, com.javahonk.model" />
	
	<tx:annotation-driven transaction-manager="transactionManager" />
	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="${jdbc.driverClassName}" />
          <property name="url" value="${jdbc.url}" />
          <property name="username" value="${jdbc.username}" />
          <property name="password" value="${jdbc.password}" />
   </bean>
   
   <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
          <property name="dataSource" ref="dataSource" />
          <property name="packagesToScan">
          	   <list>
          	   		<value>com.javahonk.model</value>
          	   		<value>com.javahonk.dao</value>          	   		
          	   </list>
          </property>
          <property name="hibernateProperties">
               <props>
                     <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                     <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                     <prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop>
                     <prop key="hibernate.c3p0.min_size">${hibernate.c3p0.min_size}</prop>
                     <prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop>
                     <prop key="hibernate.c3p0.max_statements">${hibernate.c3p0.max_statements}</prop>
                </props>
          </property>
          <property name="mappingLocations" value="hibernate.queries.xml"></property>
   </bean>
   
   <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
     <property name="sessionFactory" ref="sessionFactory"/>
   </bean>
	
</beans>
  • hibernate.queries.xml: Here you can defined hibernate queries:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>

	<query name="getEquitySwapTestData">
		<![CDATA[
			from EquitySwapTestModel esm where
				esm.eventDate = :eventDate
		]]>
	</query>
	
</hibernate-mapping>
  • spring-context.xml: Heart of the application where initialization starts for Spring framework and here you mentioned and include all your beans, configuration etc…
<?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:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	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-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
	
	<context:annotation-config />
	<context:component-scan base-package="com.javahonk.dao, com.javahonk.model" />
	
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:hibernate/hibernate.properties</value>
				<value>application.properties</value>								
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true"/>
		<property name="ignoreResourceNotFound" value="true"/>
	</bean>
	
	<import resource="hibernate-context.xml"/>

</beans>
  • EquitySwapTestModel.java: This is hibernate model class for the table which create into the database:
package com.javahonk.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="OTC..EquitySwapTest")
public class EquitySwapTestModel {
	
	@Id
	@Column(name="underlierRicCode")
	private String underlierRicCode;
	
	@Column(name="underlierSmID")
	private Integer underlierSmID;
	
	@Column(name="underlierCusip")
	private String underlierCusip;
	
	@Column(name="underlierAssetType")
	private String underlierAssetType;
	
	@Column(name="div_list_id")
	private Integer div_list_id;
	
	@Column(name="eventDate")
	private Integer eventDate;

	public String getUnderlierRicCode() {
		return underlierRicCode;
	}

	public void setUnderlierRicCode(String underlierRicCode) {
		this.underlierRicCode = underlierRicCode;
	}

	public Integer getUnderlierSmID() {
		return underlierSmID;
	}

	public void setUnderlierSmID(Integer underlierSmID) {
		this.underlierSmID = underlierSmID;
	}

	public String getUnderlierCusip() {
		return underlierCusip;
	}

	public void setUnderlierCusip(String underlierCusip) {
		this.underlierCusip = underlierCusip;
	}

	public String getUnderlierAssetType() {
		return underlierAssetType;
	}

	public void setUnderlierAssetType(String underlierAssetType) {
		this.underlierAssetType = underlierAssetType;
	}

	public Integer getDiv_list_id() {
		return div_list_id;
	}

	public void setDiv_list_id(Integer div_list_id) {
		this.div_list_id = div_list_id;
	}

	public Integer getEventDate() {
		return eventDate;
	}

	public void setEventDate(Integer eventDate) {
		this.eventDate = eventDate;
	}

	@Override
	public String toString() {
		return "EquitySwapTestModel [underlierRicCode=" + underlierRicCode
				+ ", underlierSmID=" + underlierSmID + ", underlierCusip="
				+ underlierCusip + ", underlierAssetType=" + underlierAssetType
				+ ", div_list_id=" + div_list_id + ", eventDate=" + eventDate
				+ "]";
	}
	
}
  • EquitySwapTestModelForProcedure.java: I have create another model class for to populate all data when calling the store procedure. Please pay attention on the attribute name: rowKey actually its dummy key which will be unique all time when you get data through store procedure.
package com.javahonk.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class EquitySwapTestModelForProcedure {
	
	@Id
	@Column(name="rowKey")
	private String rowKey;
	
	@Column(name="underlierRicCode")
	private String underlierRicCode;
	
	@Column(name="underlierSmID")
	private Integer underlierSmID;
	
	@Column(name="underlierCusip")
	private String underlierCusip;
	
	@Column(name="underlierAssetType")
	private String underlierAssetType;
	
	@Column(name="div_list_id")
	private Integer div_list_id;
	
	@Column(name="eventDate")
	private Integer eventDate;
	
	public EquitySwapTestModelForProcedure() {		
	}

	public String getRowKey() {
		return rowKey;
	}

	public void setRowKey(String rowKey) {
		this.rowKey = rowKey;
	}

	public String getUnderlierRicCode() {
		return underlierRicCode;
	}

	public void setUnderlierRicCode(String underlierRicCode) {
		this.underlierRicCode = underlierRicCode;
	}

	public Integer getUnderlierSmID() {
		return underlierSmID;
	}

	public void setUnderlierSmID(Integer underlierSmID) {
		this.underlierSmID = underlierSmID;
	}

	public String getUnderlierCusip() {
		return underlierCusip;
	}

	public void setUnderlierCusip(String underlierCusip) {
		this.underlierCusip = underlierCusip;
	}

	public String getUnderlierAssetType() {
		return underlierAssetType;
	}

	public void setUnderlierAssetType(String underlierAssetType) {
		this.underlierAssetType = underlierAssetType;
	}

	public Integer getDiv_list_id() {
		return div_list_id;
	}

	public void setDiv_list_id(Integer div_list_id) {
		this.div_list_id = div_list_id;
	}

	public Integer getEventDate() {
		return eventDate;
	}

	public void setEventDate(Integer eventDate) {
		this.eventDate = eventDate;
	}

	@Override
	public String toString() {
		return "EquitySwapTestModelForProcedure [rowKey=" + rowKey
				+ ", underlierRicCode=" + underlierRicCode + ", underlierSmID="
				+ underlierSmID + ", underlierCusip=" + underlierCusip
				+ ", underlierAssetType=" + underlierAssetType
				+ ", div_list_id=" + div_list_id + ", eventDate=" + eventDate
				+ "]";
	}
	
}
  • GenericDao.java: Interface for all methods definition which we will use for our testing:
package com.javahonk.dao;

import java.util.List;

public interface GenericDao<T> {
	
	public List<T> getEquitySwapByStoreProcedure(int eventDate);
	public List<T> getEquitySwapByNativeSelectQuery(int eventDate);
	public List<T> getEquitySwapByHibernateORM(int eventDate); 
	public List<T> getEquitySwapByHibernateQuery(int eventDate); 

}
  • GenericDaoHandler.java: Main implementation class where we are making call to the database. I think you will need to pay extra attention to this class because if you are creating your application just you need to find how you can make different type to call to the database:
package com.javahonk.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.javahonk.model.EquitySwapTestModel;
import com.javahonk.model.EquitySwapTestModelForProcedure;


@Repository
@Transactional
public class GenericDaoHandler<T> implements GenericDao<T>{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@Value("${query_getEquitySwapTestData}")
	private String query_getEquitySwapTestData;

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)
	public List<T> getEquitySwapByStoreProcedure(int eventDate) {
		
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createSQLQuery(
				"{CALL OTC.dbo.EquitySwapTestProcedure(:eventDate)}").addEntity(EquitySwapTestModelForProcedure.class);
		query.setParameter("eventDate", eventDate);
		List<T> dividendPayDate = query.list();
		return dividendPayDate;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getEquitySwapByNativeSelectQuery(int eventDate) {
		
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createSQLQuery("SELECT * FROM OTC.dbo.EquitySwapTest where eventDate = :eventDate").addEntity(EquitySwapTestModel.class);
		query.setParameter("eventDate", eventDate);
		List<T> dividendPayDate = query.list();
		return dividendPayDate;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getEquitySwapByHibernateORM(int eventDate) {
		
		Session session = sessionFactory.getCurrentSession();
		Query query = session.getNamedQuery(query_getEquitySwapTestData);
		query.setParameter("eventDate", eventDate);		
		List<T> dividendPayDate = query.list();
		return dividendPayDate;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getEquitySwapByHibernateQuery(int eventDate) {
		
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from EquitySwapTestModel esm where esm.eventDate = :eventDate");
		query.setParameter("eventDate", eventDate);		
		List<T> dividendPayDate = query.list();
		return dividendPayDate;
	}	

}
  • HibernateTestApp.java: Main test class to test this application:
package com.javahonk;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javahonk.dao.GenericDao;
import com.javahonk.model.EquitySwapTestModel;
import com.javahonk.model.EquitySwapTestModelForProcedure;

public class HibernateTestApp {

	private static final Logger logger = LogManager.getLogger(HibernateTestApp.class.getName());

	@SuppressWarnings({ "unchecked" })
	public static void main(String[] args) {

		logger.info("Starting HibernateTestApp...");

		ApplicationContext context = new ClassPathXmlApplicationContext(
				"spring-context.xml");

		GenericDao<?> genericDao = context.getBean(GenericDao.class);
		
		List<EquitySwapTestModelForProcedure> dataList = (List<EquitySwapTestModelForProcedure>) genericDao
				.getEquitySwapByStoreProcedure(20151028);
		logger.info("Got the data: {}", dataList);
		
		List<EquitySwapTestModel> dataList2 = (List<EquitySwapTestModel>) genericDao
				.getEquitySwapByNativeSelectQuery(20151028);
		logger.info("Got the data: {}", dataList2);
		
		dataList2 = (List<EquitySwapTestModel>) genericDao
				.getEquitySwapByHibernateORM(20151028);
		logger.info("Got the data: {}", dataList2);
		
		dataList2 = (List<EquitySwapTestModel>) genericDao
				.getEquitySwapByHibernateQuery(20151028);
		logger.info("Got the data: {}", dataList2);

		((AbstractApplicationContext) context).close();

	}

}
  • That’s it. To run this application right click HibernateTestApp.java and Run As java application and if everything setup correctly you should get all data as below:

Spring Hibernate Sybase Integration example

  • For more information please visit spring documentation here

download Download Project: SpringHibernateSysbaseIntegration

Leave a Reply

Your email address will not be published. Required fields are marked *