Friday, October 10, 2008
Tuesday, July 29, 2008
Binary Search Tree in Java with Generics
This post is more about generics than the actual implementation of the binary search tree. I tried to implement some of the suggestions in the developerworks articles titled "Java theory and practice: Going wild with generics". The Binary Search Tree of this example uses the first two suggestions. The rest are equally helpful though.
- A generic factory method that allows you to avoid redundantly specifying type parameters
public static<T extends Comparable<? super T>> BinarySearchTree<T> createTestTree()
Can be used as shown below.BinarySearchTree<Test> tree = BinarySearchTree.createTestTree();
- By using bounded wildcards, we can now construct a tree with both the super and sub-class type objects.
public class BinarySearchTree<T extends Comparable<? super T>>
- The get-put principle
Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard when you do both.
- Wildcard capture: Use a generic method as a capture helper to workaround compiler's limitations dealing with wildcards. (refer to the article "Java theory and practice: Going wild with generics, Part 1")
package trees;References
import java.util.NoSuchElementException;
public class BinarySearchTree<T extends Comparable<? super T>> {
private Entry<T> root;
public BinarySearchTree() {
root = null;
}
public static<T extends Comparable<? super T>> BinarySearchTree<T> createTestTree() {
return new BinarySearchTree<T>();
}
public void insert(T value) {
root = insert(value, root);
}
public void remove(T value) {
root = remove(value, root);
}
public boolean contains(T value) {
return valueOf(find(value, root)) != null;
}
private T valueOf(Entry<T> entry) {
return entry == null ? null : entry.element;
}
private Entry<T> insert(T value, Entry<T> entry) {
if (entry == null)
entry = new Entry<T>(value);
else if (value.compareTo(entry.element) < 0)
entry.left = insert(value, entry.left);
else if (value.compareTo(entry.element) > 0)
entry.right = insert(value, entry.right);
else
throw new RuntimeException("Duplicate Entry : " + value.toString());
return entry;
}
private Entry<T> remove(T value, Entry<T> entry) {
if (entry == null)
throw new NoSuchElementException("Entry not found : " + value.toString());
if (value.compareTo(entry.element) < 0)
entry.left = remove(value, entry.left);
else if (value.compareTo(entry.element) > 0)
entry.right = remove(value, entry.right);
else {
// Entry found.
if (entry.left != null && entry.right != null) {
// Replace with in-order successor (the left-most child of the right subtree)
entry.element = findMin(entry.right).element;
entry.right = removeInorderSuccessor(entry.right);
// Replace with in-order predecessor (the right-most child of the left subtree)
// entry.element = findMax(entry.left).element;
// entry.left = removeInorderPredecessor(entry.left);
} else
entry = (entry.left != null) ? entry.left : entry.right;
}
return entry;
}
private Entry<T> removeInorderSuccessor(Entry<T> entry) {
if (entry == null)
throw new NoSuchElementException();
else if (entry.left != null) {
entry.left = removeInorderSuccessor(entry.left);
return entry;
} else
return entry.right;
}
private Entry<T> removeInorderPredecessor(Entry<T> entry) {
if (entry == null)
throw new NoSuchElementException();
else if (entry.right != null) {
entry.right = removeInorderPredecessor(entry.right);
return entry;
} else
return entry.left;
}
private Entry<T> findMin(Entry<T> entry) {
if (entry != null)
while (entry.left != null)
entry = entry.left;
return entry;
}
private Entry<T> findMax(Entry<T> entry) {
if (entry != null)
while (entry.right != null)
entry = entry.right;
return entry;
}
private Entry<T> find(T value, Entry<T> entry) {
while (entry != null) {
if (value.compareTo(entry.element) < 0)
entry = entry.left;
else if (value.compareTo(entry.element) > 0)
entry = entry.right;
else
return entry;
}
return null;
}
private void printInOrder(Entry<T> entry) {
if (entry != null) {
printInOrder(entry.left);
System.out.println(entry.element);
printInOrder(entry.right);
}
}
public void printInOrder() {
printInOrder(root);
}
private static class Entry<T extends Comparable<? super T>> {
T element;
Entry<T> left;
Entry<T> right;
Entry(T theElement) {
element = theElement;
left = right = null;
}
}
private static class Test implements Comparable<Test> {
private String value;
public Test(String value) {
this.value = value;
}
public String toString() {
return value;
}
@Override
public int compareTo(Test o) {
return this.value.compareTo(o.toString());
}
}
private static class Test1 extends Test {
public Test1(String value) {
super(value);
}
}
public static void main(String[] args) {
BinarySearchTree<Test> tree = BinarySearchTree.createTestTree();
int size = 20;
for (int i = 0; i <= size; i++) {
tree.insert(new Test1(String.valueOf(i)));
}
tree.insert(new Test1("100"));
tree.remove(new Test1("10"));
tree.remove(new Test1(String.valueOf(15)));
tree.remove(new Test1(String.valueOf(20)));
tree.printInOrder();
System.out.println("Contains (10) : " + tree.contains(new Test1("10")));
System.out.println("Contains (11) : " + tree.contains(new Test1(String.valueOf(11))));
}
}
Monday, July 28, 2008
Cricular Linked List in Java
Had to implement a circular linked list recently. Here's my take, suggestions are welcome. The list can be parameterized for any type which has a meaningful equals method defined. The main method shows a sample usage of the Circular linked list with the String type. Only add, remove and size method are implemented.
There's more ...
There's more ...
package algo;
import java.util.NoSuchElementException;
public class CircularLinkedList<E> {
private Entry<E> head;
// Last element of the list. tail.next = head
private Entry<E> tail;
private int size = 0;
/**
* Class to hold the individual elements.
* @param <E>
*/
private static class Entry<E> {
E element;
Entry<E> next;
Entry(E element, Entry<E> next) {
this.element = element;
this.next = next;
}
Entry(E element) {
this.element = element;
}
}
public CircularLinkedList() {
head = null;
}
/**
* Remove obj from the circular linked list and return the removed object
* @param obj
* @return
*/
public E remove(E obj) {
if (head == null || tail == null)
throw new NoSuchElementException();
Entry<E> current = head, temp = head, found = null;
if (obj.equals(head.element)) {
if (head.next == head) {
found = head;
head = null;
tail = null;
size--;
return found.element;
} else {
found = head;
temp = tail;
}
} else {
current = head.next;
while (current != head) {
if (current.element.equals(obj)) {
found = current;
break;
}
temp = current;
current = current.next;
}
}
if (found == null) {
throw new NoSuchElementException(obj.toString());
}
E result = found.element;
temp.next = found.next;
found.next = null;
found.element = null;
size--;
return result;
}
/**
* Add obj to the circular linked list.
* @param obj
*/
public void add(E obj) {
Entry e = new Entry(obj);
if (head == null) {
size++;
head = e;
head.next = head;
tail = head;
return;
}
size++;
e.next = head;
head = e;
tail.next = head;
}
/**
* Size of the list.
* @return
*/
public int size() {
return size;
}
public static void main(String[] args) {
CircularLinkedList<String> list = new CircularLinkedList<String>();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
System.out.println(list.remove("Three"));
System.out.println(list.remove("Two"));
System.out.println(list.remove("One"));
System.out.println(list.remove("Four"));
System.out.println(list.remove("Four"));
}
}
Monday, July 14, 2008
Detecting Code Smells With Eclipse and CheckStyle
In a new article "Automation for the people: Continual refactoring" as a part of the "Automation for the people" series, Paul Duvall discusses the use of static code analysis tools to identify code smells and suggested refactorings. The article shows how to
There's MoreThe following is a short list of static code analysis tools available for JavaThis post describes how to identify common code smells using CheckStyle and Eclipse. Checkstyle has a useful eclipse plugin. Installing the plugin is simple. In Eclipse Ganymede,
- Reduce conditional complexity code smells by measuring cyclomatic complexity using CheckStyle and providing refactorings such as Replace Conditional with Polymorphism
- Remove duplicated code code smells by assessing code duplication using CheckStyle and providing refactorings such as Pull Up Method
- Thin large class code smells by counting source lines of code using PMD (or JavaNCSS) and providing refactorings such as Extract Method
- Wipe out too many imports code smells by determining a class's efferent coupling using CheckStyle (or JDepend) and providing refactorings such as Move Method
- Go to Help->Software Updates->Software Updates->Available Software
- Click on Add Site, and add http://eclipse-cs.sourceforge.net/update to the sites list
- Select the new site and click Install
| Conditional complexity | Metrics->Cyclomatic Complexity |
|
| Duplicated code | Duplicates->Strict Duplicate Code |
|
| Long method | Size Violations->Maximum Method Length |
|
Tuesday, July 08, 2008
Web Service Best Practices
Bobby Woolf at IBM has a list of articles with best practices for working with Web Services. Most of these links are IBM resources.
To these I'd just like to add Implementing REST Web Services: Best Practices and Guidelines, which I find useful for implementing REST based web services.
- "Best practices for Web services" series: Part 1 through Part 12 (developerWorks)
- "Web Services Architectures and Best Practices" (developerWorks)
- "Best practices for Web services versioning" (developerWorks)
- "Best Practices and Web services Profiles" (developerWorks)
- "Web services performance best practices" (WAS InfoCenter)
- "Web services migration best practices" (WAS InfoCenter)
- WebSphere Version 6 Web Services Handbook Development and Deployment (Redbook)
- Web Services Handbook for WebSphere Application Server 6.1 (Redbook)
- IBM WebSphere DataPower SOA Appliances Part III: XML Security Guide (Redbook)
- "Web services with SOAP over JMS in IBM WebSphere Process Server or IBM WebSphere Enterprise Service Bus" (developerWorks)
- "Web services SOAP/JMS protocol" (WAS InfoCenter)
- "HTTP and JMS transport methods" (RAD InfoCenter)
Thursday, April 17, 2008
Integrating Spring and Hibernate: Transactions
In the previous post, I described different ways in which spring and hibernate can
be integrated. In this post I will describe how to use Spring's transaction features
in hibernate. The following methods of transaction management with spring and hibernate are discussed.
The easiest way to check if transactions are working for this example is to remove the transaction declarations for the getStockQuote() method. Removing transactions will cause the following exception
There's More ...
For this example, start off with the following as described in the "Integrating Spring and Hibernate" post.
The following main class can be used:SpringHibernateTest.java
Note that here we use an Interface IPortfolioService, and also note the change to ApplicationContext instead of a BeanFactory.
The reason for using ApplicationContext is enable the use of AOP for declarative transaction management. Also we are not expecting any return to the main class as all the execution is expected to happen in the transaction context.
The Portfolio Service Interface:IPortfolioService.java
Declarative transaction management in Spring has the advantage of being less invasive. There is no need for changing application code when using declarative transactions. All you have to do is to modify the application context.
The Service class will be same for all the modes of Declarative transaction management described below.PortfolioService.java
In this method, you have to define a proxy for the bean that will be made transactional.applicationContext.xml
Note that the transactionInterceptor and hibernateTransactionInterceptor are declared. While transactionInterceptor is used to set the transaction properties, the hibernateTransactionInterceptor will manage the hibernate transactions.
applicationContext.xml Using Schema-based declarative transaction management is a lot simpler and a lot cleaner. However it is adviced that this method not be used in conjunction with explicit auto-proxying using BeanNameAutoProxyCreator, as it might raise issues like advice not being woven etc. Note that the AOP pointcut is defined to be all methods on the IPortfolioService inteface.
Schema-based Declarative Transaction Management with Annotations
applicationContext.xml When using annotations, you only have to declare the transaction manager and add <tx:annotation-driven/> to the application context. If the transaction manager is named "transactionManager" then you don't have to declare a transaction-manager attribute for <tx:annotation-driven/> as it happens to be the default value for that attribute.
Also we have to declare the pointcuts in the Service class itself. Note that as annotations are not inherited, declaring the annotations has to be done at the class level.
For programmatic transaction management in spring, you will need a PlatformTransctionManger in your bean which will be used to create a TransactionTemplate. The TransactionTemplate is used in the same way the HibernateTemplate was used in previous example. Additionally you will have to create a HibernateTransactionManager as shown in the above example.PortfolioService.java
be integrated. In this post I will describe how to use Spring's transaction features
in hibernate. The following methods of transaction management with spring and hibernate are discussed.
- Declarative Transaction Mangement with AOP Interceptors
- Schema-based Declarative Transaction Management
- Schema-based Declarative Transaction Management with Annotations
- Programmatic Transaction Management
The easiest way to check if transactions are working for this example is to remove the transaction declarations for the getStockQuote() method. Removing transactions will cause the following exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
There's More ...
For this example, start off with the following as described in the "Integrating Spring and Hibernate" post.
- The bean StockQuoteBean
- The Portfolio classes : PortfolioDAO, PortfolioDAOSupport and PortfolioDAOTemplate
- The hibernate mapping file stockquote.hbm.xml
The following main class can be used:
package springhibernate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringHibernateTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
IPortfolioService portfolioService = (IPortfolioService) ctx.getBean("portfolioService");
System.out.println("Portfolio Service type : " + portfolioService.getClass());
portfolioService.getStockQuote("123");
}
}
Note that here we use an Interface IPortfolioService, and also note the change to ApplicationContext instead of a BeanFactory.
The reason for using ApplicationContext is enable the use of AOP for declarative transaction management. Also we are not expecting any return to the main class as all the execution is expected to happen in the transaction context.
The Portfolio Service Interface:
package springhibernate;
import beans.StockQuoteBean;
public interface IPortfolioService {
public void getStockQuote(String id);
public void updateStockQuote(StockQuoteBean stockQuoteBean);
}
Declarative Transaction Management
Declarative transaction management in Spring has the advantage of being less invasive. There is no need for changing application code when using declarative transactions. All you have to do is to modify the application context.
The Service class will be same for all the modes of Declarative transaction management described below.
package springhibernate;
import beans.StockQuoteBean;
import dao.PortfolioDAO;
public class PortfolioService implements IPortfolioService {
private PortfolioDAO portfolioDAO;
public void getStockQuote(String id) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
System.out.println("Result in Service : " + result.getStockSymbol());
}
public void updateStockQuote(StockQuoteBean stockQuoteBean) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}
public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}
public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}
}
Declarative Transaction Management with AOP Interceptor
In this method, you have to define a proxy for the bean that will be made transactional.
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="myPortfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributeSource">
<value>springhibernate.PortfolioService.*=PROPAGATION_REQUIRED</value>
</property>
</bean>
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="portfolioService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="myPortfolioService"></property>
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Note that the transactionInterceptor and hibernateTransactionInterceptor are declared. While transactionInterceptor is used to set the transaction properties, the hibernateTransactionInterceptor will manage the hibernate transactions.
Schema-based Declarative Transaction Management
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* springhibernate.IPortfolioService.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<tx:method name="*" propagation="REQUIRES_NEW" />
</tx:attributes>
</tx:advice>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Schema-based Declarative Transaction Management with Annotations
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Also we have to declare the pointcuts in the Service class itself. Note that as annotations are not inherited, declaring the annotations has to be done at the class level.
@Transactional
public class PortfolioService implements IPortfolioService {
private PortfolioDAO portfolioDAO;...
Programmatic Transaction Management
For programmatic transaction management in spring, you will need a PlatformTransctionManger in your bean which will be used to create a TransactionTemplate. The TransactionTemplate is used in the same way the HibernateTemplate was used in previous example. Additionally you will have to create a HibernateTransactionManager as shown in the above example.
package springhibernate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import beans.StockQuoteBean;
import dao.PortfolioDAO;
public class PortfolioServiceTransaction implements IPortfolioService{
private PortfolioDAO portfolioDAO;
private PlatformTransactionManager transactionManager;
public void getStockQuote(final String id) {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(TransactionStatus status) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
System.out.println("Symbol in transaction " + result.getStockSymbol());
}
});
}
public void updateStockQuote(final StockQuoteBean stockQuoteBean) {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(TransactionStatus status) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}
});
}
public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}
}
Monday, April 14, 2008
Integrating Spring and Hibernate
This post applies to integrating Spring framework 2.5.3 and Hibernate 3.0.
The Spring framework provides extensive support for data access through the use of support classes (JdbcDaoSupport, JdbcTemplate etc.), and extensive exception hierarchy to wrap any platform specific SQLException into an exception in the spring exception hierarchy. Additionally Spring framework also provides good support for integrating with ORM technologies like Hibernate and iBatis etc. This post will show how to integrate Spring framework with Hibernate ORM. There's more ...
The Spring framework provides extensive support for data access through the use of support classes (JdbcDaoSupport, JdbcTemplate etc.), and extensive exception hierarchy to wrap any platform specific SQLException into an exception in the spring exception hierarchy. Additionally Spring framework also provides good support for integrating with ORM technologies like Hibernate and iBatis etc. This post will show how to integrate Spring framework with Hibernate ORM. There's more ...
- Create the bean: The bean here represents a simple stock quote
package beans;
public class StockQuoteBean {
private String quoteId;
private String stockSymbol;
private String name;
public String getQuoteId() {
return quoteId;
}
public void setQuoteId(String quoteId) {
this.quoteId = quoteId;
}
public String getStockSymbol() {
return stockSymbol;
}
public void setStockSymbol(String stockSymbol) {
this.stockSymbol = stockSymbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}StockQuoteBean.java - Create a Hibernate Mapping file for the bean:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.StockQuoteBean" table="STOCK_QUOTES" lazy="false">
<id name="quoteId" column="quote_id">
<generator class="assigned" />
</id>
<property name="stockSymbol">
<column name="stock_symbol" />
</property>
<property name="name">
<column name="name" />
</property>
</class>
</hibernate-mapping>stockquote.hbm.xml
The one important thing to note here is that in the declaration, a [lazy="false"] has been added to the mapping for the stockquote bean. The reason for this is that in hibernate 3, lazy initialization is turned on by default. This raises a problem when used with spring's HibernateCallback. The spring HibernateTemplate.execute() by default closes any open sessions upon completion. When used with lazy initialization you may get a LazyInitializationException like the followingorg.hibernate.LazyInitializationException: could not initialize proxy - no Session
If you want to use lazy initialization with HibernateCallback, you will have to use this within a transaction context. The javadoc for HibernateTemplate specifies this explicitlyNote that operations that return an Iterator (i.e. iterate) are supposed
to be used within Spring-driven or JTA-driven transactions (with
HibernateTransactionManager, JtaTransactionManager, or EJB CMT). Else, the
Iterator won't be able to read results from its ResultSet anymore, as the
underlying Hibernate Session will already have been closed.
Lazy loading will also just work with an open Hibernate Session, either within a
transaction or within OpenSessionInViewFilter/Interceptor. Furthermore, some
operations just make sense within transactions, for example: contains, evict,
lock, flush, clear. - The service class: The service class simply acts as an intermediary between the client and the DAO classes.
package springhibernate;
import beans.StockQuoteBean;
import dao.PortfolioDAO;
public class PortfolioService {
private PortfolioDAO portfolioDAO;
public StockQuoteBean getStockQuote(String id) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
return result;
}
public void updateStockQuote(StockQuoteBean stockQuoteBean) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}
public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}
public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}
}PortfolioService.java - The DAO interface:
package dao;
import beans.StockQuoteBean;
public interface PortfolioDAO {
public StockQuoteBean getStockQuote(String id);
public void updateStockQuote(StockQuoteBean bean);
public StockQuoteBean getStockQuote_hibernateTemplate(String id);
public void updateStockQuote_hibernateTemplate(StockQuoteBean bean);
}PortfolioDAO.java - The DAO Classes: The DAO classes shows the different ways in which the Hibernate calls can be made using the Spring support classes. There are three primary ways in which these calls can be made
- Using the HibernateCallback
- Using the HibernateTemplate directly
- Using the hibernate native calls using Session
- Using Composition, with HibernateTemplate
- Using Inheritance by extending HibernateDaoSupport
- Using HibernateTemplate
package dao;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import beans.StockQuoteBean;
public class PortfolioDAOTemplate implements PortfolioDAO{
private HibernateTemplate hibernateTemplate;
public PortfolioDAOTemplate() {
System.out.println("Init transaction dao");
}
public StockQuoteBean getStockQuote(final String id) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
return session.load(StockQuoteBean.class, id);
}
};
return (StockQuoteBean) hibernateTemplate.execute(callback);
}
public void updateStockQuote(final StockQuoteBean StockQuoteBean) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
session.saveOrUpdate(StockQuoteBean);
return null;
}
};
hibernateTemplate.execute(callback);
}
public void updateStockQuote_hibernateTemplate(StockQuoteBean StockQuoteBean) {
hibernateTemplate.update(StockQuoteBean);
}
public StockQuoteBean getStockQuote_hibernateTemplate(String id) {
List<StockQuoteBean> transactions = hibernateTemplate.find("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?", id);
return transactions.get(0);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}PortfolioDAOTemplate
This class shows how to use the HibernateTemplate to make calls to Hibernate. The getStockQuote() and updateStockQuote() methods use HibernateCallback class, note that when using HibernateCallback, it is necessary to either do it in a transactional context or turn off lazy initialization. While the getStockQuote_hibernateTemplate() and updateStockQuote_hibernateTemplate() make calls using hibernateTemplate directly. Also note that the parameters to the getStockQuote(), and updateStockQuote() methods are marked final. - Using HibernateDaoSupport
package dao;
import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import beans.StockQuoteBean;
public class PortfolioDAOSupport extends HibernateDaoSupport implements PortfolioDAO {
public void updateStockQuote(StockQuoteBean stockQuoteBean) {
Query query = getSession().createQuery("update beans.StockQuoteBean set stockSymbol=? where quoteId=?");
query.setString(0, stockQuoteBean.getStockSymbol());
query.setString(1, stockQuoteBean.getQuoteId());
query.executeUpdate();
}
public StockQuoteBean getStockQuote(String id) {
Query query = getSession().createQuery("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?");
query.setString(0, id);
List results = query.list();
if(results == null || results.size() == 0) {
throw new RuntimeException("No result");
}
return (StockQuoteBean)results.get(0);
}
public void updateStockQuote_hibernateTemplate(StockQuoteBean StockQuoteBean) {
getHibernateTemplate().update(StockQuoteBean);
}
public StockQuoteBean getStockQuote_hibernateTemplate(String id) {
List<StockQuoteBean> transactions = getHibernateTemplate().find("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?", id);
return transactions.get(0);
}
}PortfolioDAOSupport
This class uses HibernateDaoSupport to get instances of HibernateTemplate, and the Hibernate Session. The getStockQuote() and updateStockQuote() in this class make calls to hibernate session directly.
- The application context
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="portfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOSupport"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>applicationContext.xml - The SessionFactory is defined with the datasource and mapping-resources. The hibernate specific properties are defined under the hibernateProperties property.
- The HibernateTemplate uses are reference to the SessionFactory.
- The HibernateTemplate is used as a reference to the DAO classes.
- The porfolioService bean in uses a reference to the PortfolioDAO, which can be switched between the dao.PortfolioDAOSupport and dao.PortfolioDAOTemplate beans
- The main class
package springhibernate;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import beans.StockQuoteBean;
public class SpringHibernateTest {
public static void main(String[] args) {
Resource resource = new FileSystemResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
PortfolioService portfolioService = (PortfolioService) factory.getBean("portfolioService");
StockQuoteBean result = portfolioService.getStockQuote("123");
System.out.println(result.getStockSymbol());
empResult.setStockSymbol("GOOG");
portfolioService.updateStockQuote(result);
}
}SpringHibernateTest.java - Necessary JAR files:
- commons-logging-1.1.1.jar
- hibernate3.jar
- dom4j-1.6.1.jar
- ojdbc14.jar
- commons-collections-3.2.jar
- log4j-1.2.15.jar
- commons-dbcp.jar
- commons-pool.jar
- spring.jar
- cglib-nodep-2.1_3.jar
- antlr-2.7.6.jar
- jta.jar
Subscribe to:
Posts (Atom)
Popular Posts
-
This post will describe how to create and deploy a Java Web Application war to Heroku using Heroku CLI. You will need a basic understanding ...
-
The previous post described how to implement a JMS messaging client using Spring JMS . This post will describe how to implement the Message ...
-
Last week, I described how to implement JMS, using a stand-alone client and a Message Driven Bean . In this post and the next, I will descr...
-
In a previous post, I described how to use Quartz scheduler for scheduling . In this post, I describe the configuration changes required for...
-
In this post we will see how to do an offline install Jenkins and required plugins on a Red Hat Enterprise Linux Server release 7.3. This is...
-
New posts with iText 5.5.12 Following are two new posts for PDF Merge with iText 5.5.12 Merge PDF files using iText 5 Merge and Paginate PDF...
-
Redhat Enterprise Linux provides Redhat Developer Toolset , which allows you to install Git. However, it is usually an older version. If you...
-
In the past, I had a few posts on how to implement pagination using displaytag( 1 , 2 ). That solution is feasible only with small result se...
-
Acegi Security provides a comprehensive security solution for J2EE-based enterprise software applications, built using the Spring Framework...
-
Java 8 introduces default static methods that enable you to add new functionality to the interfaces of your libraries and ensure binary comp...