<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.3" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>Java Blog - Java, J2EE, SOA, Spring and Hibernate &#187; Design</title>
	<link>http://javablog.info</link>
	<description></description>
	<pubDate>Thu, 17 Apr 2008 00:24:36 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.3</generator>
	<language>en</language>
			<item>
		<title>Exception handling framework using Spring AOP</title>
		<link>http://javablog.info/2007/11/29/exception-handling-framework-using-spring-aop/</link>
		<comments>http://javablog.info/2007/11/29/exception-handling-framework-using-spring-aop/#comments</comments>
		<pubDate>Thu, 29 Nov 2007 07:39:44 +0000</pubDate>
		<dc:creator>Ravi Nallakukkala</dc:creator>
		
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">http://javablog.info/2007/04/11/exception-handling-framework-using-spring-aop/</guid>
		<description><![CDATA[In this article I will look at the various features which are required for a good exception handling framework and how Aspect oriented programming (AOP) will be used in the design of an Exception handling framework.
Lets Look at the key feature of an Exception handling framework

Propagating business and technical exceptions from the server side to [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I will look at the various features which are required for a good exception handling framework and how Aspect oriented programming (AOP) will be used in the design of an Exception handling framework.</p>
<p>Lets Look at the key feature of an Exception handling framework</p>
<ul>
<li>Propagating business and technical exceptions from the server side to the client side modules in a consistent manner.</li>
<li>Returning error codes into human readable error messages.</li>
<li>Handling checked and unchecked exceptions in a unified way.</li>
<li>Throwing checked and unchecked exceptions and creating new instances initialized with an error code picked from a predefined set.</li>
<li>Implementing new exception classes in a predefined inheritance hierarchy.</li>
</ul>
<p>Learn more about exceptions <a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/" target="_blank">here</a> and find out the difference between Checked and unchecked exceptions <a href="http://www.javapractices.com/Topic129.cjp" target="_blank">here</a>.</p>
<p>By large, Exceptions are classified in two categories</p>
<p> <a href="http://javablog.info/2007/11/29/exception-handling-framework-using-spring-aop/#more-29" class="more-link">(more&#8230;)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://javablog.info/2007/11/29/exception-handling-framework-using-spring-aop/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Spring Based JUnit Integration Test approach</title>
		<link>http://javablog.info/2007/11/29/spring-based-junit-integration-tests/</link>
		<comments>http://javablog.info/2007/11/29/spring-based-junit-integration-tests/#comments</comments>
		<pubDate>Thu, 29 Nov 2007 04:13:58 +0000</pubDate>
		<dc:creator>Ravi Nallakukkala</dc:creator>
		
		<category><![CDATA[Design]]></category>

		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://javablog.info/2007/04/09/spring-based-junit-integration-tests/</guid>
		<description><![CDATA[The Spring Framework provides a good support for the integration tests for enterprise software applications and these support classes are packaged in spring-mock.jar and all these classes are JUnit test classes. org.springframework.test package provides valuable JUnit TestCase superclasses for integration testing using a Spring container and this approach is completely independent of any web/ application [...]]]></description>
			<content:encoded><![CDATA[<p>The Spring Framework provides a good support for the integration tests for enterprise software applications and these support classes are packaged in spring-mock.jar and all these classes are JUnit test classes. org.springframework.test package provides valuable JUnit TestCase superclasses for integration testing using a Spring container and this approach is completely independent of any web/ application server.</p>
<p>Spring out-of-box provide the following functionality:</p>
<ul>
<li>Transaction management though spring container.</li>
<li>Dependency Injection feature.</li>
<li>Spring Ioc Container caching between execution.</li>
</ul>
<p>On Surface, Spring Test cases can be classified into</p>
<ul>
<li>JUnit with Dependency Injection.</li>
<li>Junit with Dependency Injection and Transactional Control.</li>
</ul>
<p><strong>Spring based JUnit with Dependency Injection</strong></p>
<p>For JUnit Classes which need to use Dependency injection feature of spring will be required to inherit the class â€˜AbstractDependencyInjectionSpringContextTestsâ€˜ and the subclass need to implement the superclassâ€™s abstract method â€˜protected abstract String[] getConfigLocations();â€™ the implementation of this method need to return the spring configuration XML files which are required to participate in the execution of the test case.<br />
E.g,<br />
public final class ExampleDaoTests extends <strong>AbstractDependencyInjectionSpringContextTests</strong>  {</p>
<p>// this reference will be automatically injected through spring<br />
private ExampleDao exampleDao;</p>
<p>// a setter method to enable DI for the Dao instance variable<br />
public void setExampleDao(ExampleDao exampleDao) {<br />
this.exampleDao = exampleDao;<br />
}</p>
<p>public void testExample() throws Exception {<br />
BusinessObject bo = this.exampleDao.loadBo(new Long(10));<br />
assertNotNull(title);<br />
}</p>
<p>// specifies the Spring configuration to load for this test.<br />
protected String[] getConfigLocations() {<br />
return new String[] { â€œclasspath:com/foo/daos.xmlâ€ };<br />
}<br />
}</p>
<p><strong>&lt;&lt; Spring Configuration file &gt;&gt;</strong></p>
<p>&lt;?xml version=â€1.0? encoding=â€UTF-8??&gt;<br />
&lt;!DOCTYPE beans PUBLIC  â€œ-//SPRING//DTD BEAN 2.0//ENâ€<br />
â€œhttp://www.springframework.org/dtd/http://www.springframework.org/dtd/spring-beans-2.0.dtdâ€&gt;<br />
&lt;beans&gt;</p>
<p>&lt;!â€“ this bean will be injected into the ExampleDaoTests class â€“&gt;<br />
&lt;bean id=â€exampleDaoâ€ class=â€com.foo.dao.hibernate.ExampleDaoâ€&gt;<br />
&lt;property name=â€sessionFactoryâ€ ref=â€sessionFactoryâ€/&gt;<br />
&lt;/bean&gt;</p>
<p>&lt;bean id=â€sessionFactoryâ€ class=â€org.springframework.orm.hibernate3.LocalSessionFactoryBeanâ€&gt;<br />
&lt;!â€“ dependencies elided for clarity â€“&gt;<br />
&lt;/bean&gt;<br />
&lt;/beans&gt;</p>
<p><strong>Spring based JUnit with Transaction Control/ Integration Test</strong></p>
<p>One common problem in integration test is to access a database and still maintain the state of the persistence store. When using a database, changes to the database state may effect the future tests and CURD operations canâ€™t be verified outside a transaction.</p>
<p>The org.springframework.test.AbstractTransactionalSpringContextTests superclass (and subclasses) exist to meet this requirement. By default, this class create and rollback a transaction for each test. From a developer/ development point of view, You simply write code that assumes the existence of a transaction.</p>
<p>It has to be noted that, this class extends AbstractDependencyInjectionSpringContextTests so spring dependency injection is made available for all the subclasses extending AbstractTransactionalSpringContextTests</p>
<p>Spring based JUnit also provides an option to commit a transaction (unusual, but occasionally useful when you want a particular test to populate the database) - you can invoke the setComplete() method inherited from AbstractTransactionalSpringContextTests. This will force the transaction to commit instead of roll back.</p>
<p>There is also convenient ability to end a transaction before the test case ends, through calling the endTransaction() method. This will roll back the transaction by default, and commit it only if setComplete() had previously been called. This functionality is useful if you want to test the behavior of â€˜disconnectedâ€™ data objects, such as Hibernate-mapped objects that will be used in a web or remoting tier outside a transaction. Often, lazy loading errors are discovered only through UI testing; if you call endTransaction() you can ensure correct operation of the UI through your JUnit test suite.<br />
E.g,</p>
<p>//as this test class extends â€˜AbstractTransactionalSpringContextTestsâ€™ so all the<br />
//test methods will be bound with a transaction.<br />
public final class ExampleDaoTests extends <strong>AbstractTransactionalSpringContextTests </strong> {</p>
<p>// this reference will be automatically injected through spring<br />
private ExampleDao exampleDao;</p>
<p>// a setter method to enable DI for the Dao instance variable<br />
public void setExampleDao(ExampleDao exampleDao) {<br />
this.exampleDao = exampleDao;<br />
}</p>
<p>public void testExample() throws Exception {<br />
BusinessObject bo = createBo(); // create the Business Objects<br />
exampleDao.create(bo); // Business Object will be created</p>
<p>//now retrieve the object which was created in the database.<br />
BusinessObject returnedObject = exampleDao.findById(bo.getId());<br />
assertEquals(bo.getId(), returnedObject.getId());<br />
//after the execution of the test method, data which was inse<br />
}</p>
<p>// specifies the Spring configuration to load for this test.<br />
protected String[] getConfigLocations() {<br />
return new String[] { â€œclasspath:com/foo/daos.xmlâ€ };<br />
}<br />
}</p>
<p><strong>&lt;&lt; Spring Configuration file &gt;&gt;</strong></p>
<p>&lt;?xml version=â€1.0? encoding=â€UTF-8??&gt;<br />
&lt;!DOCTYPE beans PUBLIC  â€œ-//SPRING//DTD BEAN 2.0//ENâ€<br />
â€œhttp://www.springframework.org/dtd/http://www.springframework.org/dtd/spring-beans-2.0.dtdâ€&gt;<br />
&lt;beans&gt;</p>
<p>&lt;!â€“ this bean will be injected into the ExampleDaoTests class â€“&gt;<br />
&lt;bean id=â€exampleDaoâ€ class=â€com.foo.dao.hibernate.ExampleDaoâ€&gt;<br />
&lt;property name=â€sessionFactoryâ€ ref=â€sessionFactoryâ€/&gt;<br />
&lt;/bean&gt;</p>
<p>&lt;bean id=â€sessionFactoryâ€ class=â€org.springframework.orm.hibernate3.LocalSessionFactoryBeanâ€&gt;<br />
&lt;!â€“ dependencies elided for clarity â€“&gt;<br />
&lt;/bean&gt;</p>
<p>&lt;/beans&gt;</p>
]]></content:encoded>
			<wfw:commentRss>http://javablog.info/2007/11/29/spring-based-junit-integration-tests/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Equals and hashcode Approach/ Implementation for Business Objects (Bo)</title>
		<link>http://javablog.info/2007/04/15/equals-and-hashcode-implementation-for-business-objects-bo/</link>
		<comments>http://javablog.info/2007/04/15/equals-and-hashcode-implementation-for-business-objects-bo/#comments</comments>
		<pubDate>Sun, 15 Apr 2007 07:58:37 +0000</pubDate>
		<dc:creator>Ravi Nallakukkala</dc:creator>
		
		<category><![CDATA[Design]]></category>

		<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://javablog.info/2007/04/15/equals-and-hashcode-implementation-for-business-objects-bo/</guid>
		<description><![CDATA[A common source for bugs while writing code Business Objects for relational database using Object Relation Mapping tools is the implementation of the Equals and Hashcode methods.
If you would like to know more about the Equals and Hashcode importance for an ORM  Click here.
To summarize the ORM implementation, There are two types of keys: [...]]]></description>
			<content:encoded><![CDATA[<p>A common source for bugs while writing code Business Objects for relational database using Object Relation Mapping tools is the implementation of the Equals and Hashcode methods.</p>
<p>If you would like to know more about the Equals and Hashcode importance for an ORM  <a href="http://www.hibernate.org/109.html" target="_blank">Click here.</a></p>
<p>To summarize the ORM implementation, There are two types of keys: Technical Keys and Business keys.</p>
<p>Technical keys are the primary key on the for a table to uniquely identify a database row, these numbers are auto generated sequence number (Item Unique IDentification/ IUID).</p>
<p>Business keys are the Business primary (/ composite) keys which uniquely identify the business objects   in the database tables.</p>
<p>One of the important factor while writing a equals and hashcode method is to decide on what attributes needs to go into these methods; Some guidelines for deciding the attributes for Equals and hashcode methods.</p>
<ul>
<li>It is not necessary to cover all the attributes in Business Objects in equals/ hashcode methods.</li>
<li>Include the Technical Keys and Business keys in equals and hashcode methods.</li>
<li>Equals and hashcode methods should take care of the null cases.</li>
</ul>
<p>Implementation wise, <a href="http://projects.apache.org/projects/jakarta_commons_lang.html" target="_blank">Apache commons-lang </a>has a very good implementation for hashcode and equals method. Here&#8217;s an example of equals and hashcode methods using the apache commons-lang<code>.</code></p>
<p><code> @Entity<br />
@Table(name = "APP_CONFIGURATION")<br />
@SequenceGenerator(name = "OPS_SEQ", sequenceName = "SQ_CONFIGURATION_CNTR")<br />
public class ConfigurationBo extends AbstractBo {</code></p>
<p>private static final long serialVersionUID = -5098377177228374794L;</p>
<p>@Column(name = &#8220;ITEMNAME&#8221;, length = 100)<br />
private String name;</p>
<p>@Column(name = &#8220;STRINGVALUE&#8221;, length = 100)<br />
private String stringValue;</p>
<p>@Column(name = &#8220;INTVALUE&#8221;)<br />
private Integer intValue;</p>
<p>@Column(name = &#8220;TYPENAME&#8221;, length = 20)<br />
private String type;</p>
<p>public Integer getIntValue() {<br />
return intValue;<br />
}</p>
<p>public void setIntValue(Integer intValue) {<br />
this.intValue = intValue;<br />
}</p>
<p>public String getName() {<br />
return name;<br />
}</p>
<p>public void setName(String name) {<br />
this.name = name;<br />
}</p>
<p>public String getStringValue() {<br />
return stringValue;<br />
}</p>
<p>public void setStringValue(String stringValue) {<br />
this.stringValue = stringValue;<br />
}</p>
<p>public String getType() {<br />
return type;<br />
}</p>
<p>public void setType(String type) {<br />
this.type = type;<br />
}</p>
<p>/**<br />
* {@inheritDoc}<br />
*/<br />
@Override<br />
public boolean equals(Object obj) {<br />
if (this == obj) {<br />
return true;<br />
}<br />
if (!(obj.getClass() == this.getClass())) {<br />
return false;<br />
}<br />
ConfigurationBo other = (ConfigurationBo) obj;</p>
<p>return new EqualsBuilder()<br />
.appendSuper(super.equals(obj))<br />
.append(this.name, other.name)<br />
.append(this.type, other.type)<br />
.isEquals();<br />
}</p>
<p>/**<br />
* {@inheritDoc}<br />
*/<br />
@Override<br />
public int hashCode() {<br />
return new HashCodeBuilder()<br />
.appendSuper(super.hashCode())<br />
.append(this.name)<br />
.append(this.type)<br />
.toHashCode();<br />
}</p>
<p>/**<br />
* {@inheritDoc}<br />
*/<br />
@Override<br />
public String toString() {<br />
return super.toString() + &#8220;[name=&#8221; + name + &#8220;, type=&#8221; + type + &#8220;]&#8221;;<br />
}</p>
<p>}</p>
]]></content:encoded>
			<wfw:commentRss>http://javablog.info/2007/04/15/equals-and-hashcode-implementation-for-business-objects-bo/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Unit Testing - Junit Approach</title>
		<link>http://javablog.info/2007/04/08/unit-testing-junit-approach/</link>
		<comments>http://javablog.info/2007/04/08/unit-testing-junit-approach/#comments</comments>
		<pubDate>Sun, 08 Apr 2007 19:56:32 +0000</pubDate>
		<dc:creator>Ravi Nallakukkala</dc:creator>
		
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">http://javablog.info/2007/04/08/unit-testing-junit-approach/</guid>
		<description><![CDATA[Unit Testing involves testing unit components or modules of Code and validating that they work properly. Itâ€™s a proactive procedure, which means that code written by developers needs to be unit tested at the unit level. All test cases are independent of each other and are to be written and executed by development team.
Prior fixing [...]]]></description>
			<content:encoded><![CDATA[<p>Unit Testing involves testing unit components or modules of Code and validating that they work properly. Itâ€™s a proactive procedure, which means that code written by developers needs to be unit tested at the unit level. All test cases are independent of each other and are to be written and executed by development team.</p>
<p>Prior fixing a bug, write a unit test to reproduce it. When the bug is fixed, verify the fix using the unit test. All methods need to be covered by the tests. The tests need to covers all paths through the unit. Unit Tests will ensure errors are picked up at the earlier stage and will facilitate easy integration.</p>
<p><strong>Unit Testing Process</strong></p>
<p>The figure below illustrates the Unit Testing Procedure and it encourages developers to write test cases before they start developing their use cases.</p>
<p><img src="/images/Junitapproach.JPG" title="Unit test life cycle" alt="Unit test life cycle" align="middle" height="522" width="346" /></p>
<p><strong>Guidelines for Unit Test Cases</strong></p>
<ul>
<li>Write the test before implementing the functionality using a test driven approach. Every software component (business modules, services, DAOs, models or controllers of the presentation tier) will be designed to be tested.</li>
<li>When a bug is identified in the code and later fixed, as a good practice write a unit test to validate it.</li>
<li>Use Mock Object to collaborate with other components.</li>
<li>Write the tests for normal success case, boundary conditions or any exceptional conditions.</li>
<li>Make a decision if itâ€™s really appropriate to write tests for simple methods or simple classes. These will get tested later during Integration Testing (like DTOs, get/set,..).</li>
<li>Unit Test for Business Objects that only encapsulate data is not necessary. Only if the BO implements Business Logic, then this has to be tested using a unit test.</li>
<li>While testing the Business Logic Layer, unit tests need to be written for every service interface. Use Mock Objects for DAOâ€™s. Components used within the service implementation that contain validation logic will need to be tested independently. E.g. Validators, Convertors.</li>
<li>For the Presentation Layer one would need to set up the page, pageView, pageModel and the PageContext. Mock Objects will be used to model the PageContext.</li>
<li>The Test Coverage should be continuously monitored. Clover/ Cobertura could be used to for code coverage.</li>
<li>The names of Java source files for testing end with â€˜Testâ€™, as in MyClassTest.java.</li>
<li>While testing the Data Access Layer, make sure every DAO method has been tested. After each test the transaction should be rolled back so cleaning of the database is not required. (spring framework will do job of automatic rollback of data changes to the database).</li>
</ul>
<p><strong>Unit Testing Tools<br />
</strong>Consider a combination of JUnit and EasyMock to write Unit Test Cases. These tools are integrated with Eclipse (hopefully with Intellij) to merge unit tests with the development process.</p>
<p><strong>Unit Testing Framework - JUnit </strong><br />
JUnit provides a Java based framework for unit testing. In order to setup JUnit one has to download the junit.jar file which is freely downloadable and append it to your classpath. JUnit will be integrated with the Eclipse development environment.</p>
<ul>
<li>While writing unit tests, any class that contains test methods should subclass the TestCase class. A TestCase can define any number of public testXXX() methods.</li>
<li>To check the expected and the actual test results, one has to invoke the variation of assert() method.</li>
<li>The Test Class having several testXXX() methods can use the setup() and teardown() methods to initialize and release any common objects under test.</li>
<li>TestCase instances can be composed into TestSuite hierarchies so that all test methods are invoked</li>
</ul>
<p><strong>EasyMock<br />
</strong>EasyMock, an open source library provides an easy medium to generate mock objects for a given interface. This facilitates running Junit tests for individual classes with the collaborators being simulated with Easy Mock Objects.</p>
<p>To get a Mock Object, we need to perform the following steps:</p>
<ul>
<li>Create a Mock Object for the interface we would like to simulate</li>
<li>Setup the Expected behavior. Record the expected method calls.</li>
<li>Switch the Mock Object to replay state. If no expected behavior is set, then call to any methods of the collaborator class with throw an exceptions.</li>
<li>Call object under test</li>
<li>Validate if the expectations have been met.</li>
<li>Code Snippet using JUnit &amp; EasyMock</li>
</ul>
<p>import junit.framework.TestCase;<br />
import static org.easymock.EasyMock.createMock;<br />
import static org.easymock.EasyMock.expect;<br />
import static org.easymock.EasyMock.replay;<br />
import static org.easymock.EasyMock.reset;<br />
import static org.easymock.EasyMock.verify;</p>
<p>public class UserServiceImplTest extends TestCase {<br />
private UserDao userDaoMock;<br />
private UserService us;<br />
public void setUp() throws Exception {</p>
<p>// 1. create the mock for our DAO<br />
userDaoMock = createMock(UserDao.class);</p>
<p>// 2. create an instance of the class under test<br />
us = new UserServiceImpl();</p>
<p>// 3. wire test object and mock<br />
us.setUserDao(userDaoMock);</p>
<p>}</p>
<p>/**<br />
* after each test method call the mock has to be reset<br />
*/<br />
public void tearDown() throws Exception {<br />
reset(userDaoMock);<br />
}<br />
}</p>
]]></content:encoded>
			<wfw:commentRss>http://javablog.info/2007/04/08/unit-testing-junit-approach/feed/</wfw:commentRss>
		</item>
		<item>
		<title>SOA based Search Design - Handling of bulk data on server side</title>
		<link>http://javablog.info/2007/04/01/search-design-handling-bulk-data-on-server-side/</link>
		<comments>http://javablog.info/2007/04/01/search-design-handling-bulk-data-on-server-side/#comments</comments>
		<pubDate>Sun, 01 Apr 2007 05:10:20 +0000</pubDate>
		<dc:creator>Ravi Nallakukkala</dc:creator>
		
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">http://javablog.info/2007/04/01/search-design-handling-bulk-data-on-server-side/</guid>
		<description><![CDATA[Its me again, For past few days my life is all about searching, search criteria and analyzing its result. The product I work has to scale up-to returning search results of the magnitude of  few hundred records. Unfortunately we don&#8217;t have the luxury of having the pagination for these search results, hence there is [...]]]></description>
			<content:encoded><![CDATA[<p>Its me again, For past few days my life is all about searching, search criteria and analyzing its result. The product I work has to scale up-to returning search results of the magnitude of  few hundred records. Unfortunately we don&#8217;t have the luxury of having the pagination for these search results, hence there is a high amount of tuning required on the server side.</p>
<p>In this article I will be describing a SOA based search design for handling bulk data in a multi layered architecture; The project I was working was architect to have 3 layers: Facade Layer, Services Layer and a DAO Layer.</p>
<p>Facade layer was implemented though EJB 3 and as expected was the main communication interface for the client, our clients  talk to the server side Facade though the Data Transfer Objects (Dto); One of the main responsibility of the facade is to convert Dto objects passed by the clients to the Business Object (Bo) for request processing and during response scenario, facade also converts the Business objects to the Dto and send the response to the client.</p>
<p>Service Layer is the place where the main business logic will placed,the communication to/ from the services layers always happens through the Business Objects. Main responsibilities of this layer include invoking the Data Access Object Layer (Dao) and invoking other Services.</p>
<p>Data Access Object Layer is mainly responsible for invoking the persistence api (most of the cases, it will be ORM like hibernate, JPA).</p>
<p>To achieve the flexibility in the design approach, Dto are used to communicate between the client and server, but it has to be noted that all the processing on the server side happens on Business Objects.</p>
<p>Considering  this architecture, Even for a search case too, search criteria will be passed to the server in the form of a Dto, and in the facade layer this search criteria dto will be converted to a Bo and then the criteria in the form of a Business object will be passed to the Dao and based on the persistence technology an appropriate query will be executed and the results in the form of the Bo will be returned to the facade, where again the Bo will be converted to the Dto objects.</p>
<p>Now, this approach works very well for low to medium volume search result sites; in order to optimize this search we have been looking around for some options and finally arrived at saying &#8220;For searches, why not allow the criteria (Dto equivalent) to be passed to the Dao layer and get the results from Dao in the form of Dto&#8221;. Essentially, all we are doing is eliminating the conversions from Bo to Dto and vice-versa. For large volume Search results, the conversation to/ from Dto/Bo makes a big differences (time consuming process). This approach also gives us a flexibility of selecting any specific attribute in an entity (unlike the case-of the Query though Business Objects, the entire Business Object will be loaded even though you need a single attribute of that entity)</p>
<p>There is already some support by JPA to support this kind of architecture for searches, for example  look at the following query</p>
<p style="font-weight: bold">select new com.alpha.beta.SearchResult(emp.id, emp.name, emp.salary) from Employee emp</p>
<p style="font-weight: bold"><span style="font-weight: normal">Now the &#8216;SearchResult&#8217; class should have a constructor matching to the above construct</span></p>
<p style="font-weight: bold"><span style="font-weight: normal">i.e,</span></p>
<p style="font-weight: bold"><span style="font-weight: normal">public class SearchResult{</span><br style="font-weight: normal" /><br style="font-weight: normal" /><span style="font-weight: normal">private Long id;</span><br style="font-weight: normal" /><span style="font-weight: normal">private String name;</span><br style="font-weight: normal" /><span style="font-weight: normal">private BigDecimal salary;</span><br style="font-weight: normal" /><br style="font-weight: normal" /><span style="font-weight: normal">    public SearchResult(Long id, String name,BigDecimal sal){</span><br style="font-weight: normal" /><span style="font-weight: normal">        this.id = id;</span><br style="font-weight: normal" /><span style="font-weight: normal">        this.name = name;</span><br style="font-weight: normal" /><span style="font-weight: normal">        this.salary = sal</span><br style="font-weight: normal" /><span style="font-weight: normal">    }</span><br style="font-weight: normal" /><span style="font-weight: normal">}</span></p>
<p style="font-weight: bold"><span style="font-weight: normal">If</span> <span style="font-weight: normal">the query retuns a &#8216;List&#8217;, In this example the list will contain a list of &#8216;SearchResult&#8217; Objects.</span></p>
<p style="font-weight: bold"><span style="font-weight: normal">To Summarize the advantage of this approach (of bi-passing the layers for search)</span></p>
<ul>
<li>There is no extra conversation To / From Dto/ Bo.</li>
<li>It also possible for some cases to load the attribute without loading the entire Business Object.</li>
<li>This approach also leaves the developer to use native SQL for complex sql which may not be implemented through some Persistence API.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://javablog.info/2007/04/01/search-design-handling-bulk-data-on-server-side/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Search Pagination Design (Server side pagination using Hibernate)</title>
		<link>http://javablog.info/2007/03/30/search-pagination-design-server-side-pagination-using-hibernate/</link>
		<comments>http://javablog.info/2007/03/30/search-pagination-design-server-side-pagination-using-hibernate/#comments</comments>
		<pubDate>Fri, 30 Mar 2007 20:45:50 +0000</pubDate>
		<dc:creator>Ravi Nallakukkala</dc:creator>
		
		<category><![CDATA[Design]]></category>

		<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://javablog.info/2007/03/30/search-pagination-design-server-side-pagination-using-hibernate/</guid>
		<description><![CDATA[One of the biggest problem which is commonly faced in searches is pagination; On the first day of my new job, I was asked to looked the performance issues related in the search functionality of the application. When I looked at the application, application is slow when the users gets a search results of magnitude [...]]]></description>
			<content:encoded><![CDATA[<p>One of the biggest problem which is commonly faced in searches is pagination; On the first day of my new job, I was asked to looked the performance issues related in the search functionality of the application. When I looked at the application, application is slow when the users gets a search results of magnitude of 6000 records( each record had 10 fields to be displayed) and all the results were displayed in a single HTML page (Even if you had designed one search implementation, you would have guessed what the problem is).</p>
<p>There is no pagination concept implemented for this search/ problem, its a logical  thing to say this search program is using whole lots of memory and slow. Assuming the search queries are already fine-tuned, Slowness can be mainly attributed to the HTML rendering by the browser. IE browser render the complete HTML and then displays it to the user so the slowness can be easily be found compared to Firefox 2, where the browser starts displaying the data as it receives (rather completely render it and displays it).</p>
<p>Given this background, Now we started seriously looking at pagination as the only option. In pagination, could think three approaches as a potential solutions</p>
<ul>
<li>Real time pagination on the server side.</li>
<li>Criteria Caching based pagination on Server side.</li>
<li>Pagination on the UI front.</li>
</ul>
<p>Lets go in details of each one of them.</p>
<p><strong>Real time pagination on the server side :</strong></p>
<p>This is an approach where from the UI, always pass the search criteria plus the page start record and the end record (or size of the page). So your server implementation will have these two extra arguments along with your query and returns you only the required result set which needs to be passed to front end.</p>
<p>On the implementation front, you could handle this scenario at two levels</p>
<ul>
<li>Write a stored procedure which takes your criteria and start and end record (or Size)  for the page as argument and using &#8216;cursors&#8217;  you can return only the required result set, for more details on oracle specific result set using cursor <a href="http://asktom.oracle.com/tkyte/ResultSets/index.html" target="_blank"><strong>click here</strong></a></li>
<li>Say you are using ORM tools like hibernate, they make our life even easier you could try something like <strong><br />
</strong></li>
</ul>
<p>Query q = s.createQuery( &#8220;your query&#8230;.&#8221; );<br />
q.setMaxResults(PAGE_SIZE);<br />
q.setFirstResult(PAGE_SIZE * pageNumber);<br />
List page = q.list();</p>
<ul>
<li>For more details on this hibernate approach <a href="http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html" target="_blank"><strong>click here</strong></a></li>
</ul>
<p>Lets looks at the pros and cons of this approach</p>
<ul>
<li>Its a real time pagination search, say your query is based on order by name, on the first page we show say 25 records, in the mean while say another user deletes few records (say 20 to 25th record gets deleted), now when the first user click the next button, the request goes as original criteria and retrieve the records from 26th to 50th record and we return 26 to 50 th records (because of the deletion, ideally we should have displayed from 20th to 45th records), essentially now we are not showing 5 records this is a disadvantage. For the same example, addition of records &#8216;could&#8217; be an advantage for this approach.</li>
</ul>
<p><strong>Criteria Caching based pagination on Server side</strong></p>
<p>This is an approach where all records matching to the search criteria will be fetched from the database to the the server and cached. Caching is based the search criteria and a timeout period.</p>
<p>From the UI point of view, request will contain the search criteria plus the start record and the size( r the end record) to be fetched.</p>
<p>Lets looks at the pros and cons of this approach</p>
<ul>
<li>This solution should fairly work for most of the search cases, unless you have a requirement for real time pagination.</li>
<li>When Caching is considered, Caching algorithm plays an important role and this also has to take care of the timeout period and the memory allocated for the caching mechanism.</li>
<li>Arriving on the timeout period is quite crucial as this directly impacts your performance of the search. Too low timeout (is very near to real time pagination case) will cause too many hits to your database and can cause slowness also has the drawbacks of real time pagination. Too long timeout period will have the drawback of having out-dated data on the server cache.</li>
</ul>
<p><strong>Pagination on the UI front</strong></p>
<p>This is an approach where all the records corresponding the search criteria will be retrieved from the database and held in the controller of the UI Framework and using custom tag libraries the records could be displayed in the Jsp/ Servlet.</p>
<p>Here are some of the recommendations for writing your own custom pagination tab lib</p>
<ul>
<li>The bean will have attributes for collection of all the records, total number of pages, records per page and start record number for the current page.</li>
<li>On the first display of the page, read all the corresponding records for this page and store the bean in HTTP Session.</li>
<li>On the selection of the next page, previous page, etc.,;  retrieve the bean from the HTTP Session and then calculate which data needs to be displayed.</li>
</ul>
<p>Lets looks at the pros and cons of this approach</p>
<ul>
<li>This would be dream design approach for small volume search results (where memory is not a constraint).</li>
<li>Most the cases, you do have a memory constraint, hence this may not be a feasible approach.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://javablog.info/2007/03/30/search-pagination-design-server-side-pagination-using-hibernate/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
