<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-5403612535047815315</id><updated>2011-11-28T04:52:43.054+05:00</updated><category term='Hibernate'/><category term='TestNG'/><category term='GWT'/><category term='Spring'/><category term='Integration'/><category term='Android'/><category term='Test'/><category term='Unit'/><title type='text'>Stuff about Java and technology</title><subtitle type='html'>I am a Java Developer and Enthusiast. I love all stuff regarding core Java and problem solving in general.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://nabeelalimemon.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://nabeelalimemon.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Nabeel Ali Memon</name><uri>http://www.blogger.com/profile/02353619277056408053</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>6</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-5403612535047815315.post-1477991364769956623</id><published>2010-07-02T00:11:00.003+05:00</published><updated>2010-07-02T01:28:07.901+05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Android'/><title type='text'>Building Android kernel from source</title><content type='html'>So, you wanna build the Android kernel from source. Great, that's a cool thing to do. I assume that you'r already using a Linux distribution (and probably Ubuntu). If not, go get &lt;a href="http://www.ubuntu.com/desktop/get-ubuntu/download"&gt;Ubuntu&lt;/a&gt;&amp;nbsp;first.&lt;br /&gt;&lt;br /&gt;To build the kernel image from source you need tools like:&lt;br /&gt;&lt;br /&gt;1-&amp;nbsp;&lt;a href="http://developer.android.com/sdk/index.html"&gt;Android SDK for Linux&lt;/a&gt;&amp;nbsp;(add path-to-sdk/tools to system path)&lt;br /&gt;&lt;br /&gt;2- Oracle's/Sun Microsystem's JDK set to your system path. I have built using JDK1.5, you can try JDK1.6 and it should work.&lt;br /&gt;&lt;br /&gt;3- From ubuntu repository, install the following tools:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;g++, perl, bison, flex, zlib1g-dev, x11proto-core-dev and libx11-dev&lt;/li&gt;&lt;li&gt;&lt;a href="http://android-dls.com/files/linux/fastboot"&gt;fastboot&lt;/a&gt; (move it under your sdk/tools/.)&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;4- Get the&amp;nbsp;&lt;a href="http://developer.android.com/sdk/ndk/index.html"&gt;Android NDK&lt;/a&gt;&amp;nbsp;for linux to get some native tools&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;5- Clone the Git repo of kernel source and switch to branch (2.6.32 is currently the latest one)&lt;br /&gt;&lt;ul&gt;&lt;li&gt;git clone git://android.git.kernel.org/kernel/msm.git&lt;/li&gt;&lt;li&gt;cd msm&lt;/li&gt;&lt;li&gt;git checkout origin/android-msm-2.6.32&lt;/li&gt;&lt;/ul&gt;6A- Before you build the source, you need to have a .config file which you can auto-generate using&lt;br /&gt;&lt;ul&gt;&lt;li&gt;make msm_defconfig&lt;/li&gt;&lt;/ul&gt;6B- Or get it from your phone using following commands:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;adb pull /proc/config.gz .&lt;/li&gt;&lt;li&gt; gunzip config.gz &lt;/li&gt;&lt;li&gt;mv config .config&lt;/li&gt;&lt;/ul&gt;7- Now you can make the build giving the platform arguments:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;make -j2 ARCH=arm CROSS_COMPILE=android-ndk/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-&lt;/li&gt;&lt;/ul&gt;Relax, and have a cup of Java before the build completes.&lt;br /&gt;&lt;br /&gt;You can boot this image in the emulator that comes with the SDK.&lt;br /&gt;&lt;ul&gt;&lt;li&gt;emulator -kernel arch/arm/boot/zImage&lt;/li&gt;&lt;/ul&gt;Or more interestingly, you can also boot from phone's RAM using 'fastboot' (make sure 'adb devices' lists your attached device):&lt;br /&gt;&lt;ul&gt;&lt;li&gt;fastboot boot arch/arm/boot/zImage&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;P.S: If you find some confusion, have some suggestions or need more stuff, the comments' area is always open for you.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5403612535047815315-1477991364769956623?l=nabeelalimemon.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nabeelalimemon.blogspot.com/feeds/1477991364769956623/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/07/building-android-kernel-from-source.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/1477991364769956623'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/1477991364769956623'/><link rel='alternate' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/07/building-android-kernel-from-source.html' title='Building Android kernel from source'/><author><name>Nabeel Ali Memon</name><uri>http://www.blogger.com/profile/02353619277056408053</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5403612535047815315.post-504395073982198828</id><published>2010-06-12T00:40:00.003+05:00</published><updated>2010-06-13T02:06:43.211+05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='GWT'/><title type='text'>Gwt-coded Presentations</title><content type='html'>Yes, a presentation but not built on Google Docs(I din't consider Powerpoint or OpenOffice since I love web as a platform). I was just looking for some fun time so I thought maybe I should _code_ my slides instead of writing them. &lt;br /&gt;&lt;br /&gt;I searched for a GWT API to do so but din't find any. So instead of wasting more time looking for such API I started writing my own app on bare GWT. It was a lot of fun writing and then actually using that app for presentation. &lt;br /&gt;&lt;br /&gt;Although currently, it's cleanly coded but since I had to build something from scratch in just one day, I left behind many design considerations in my mind which i'm gonna put into this app to make it work out more sophisticated presentations.&lt;br /&gt;&lt;br /&gt;You can have your own copy of this code (it's completely open-source under Apache 2 License), use it, improve it, give your suggestions/patches or a couple of words about what you think.&lt;br /&gt;&lt;br /&gt;The repo can be found at:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://github.com/nabeelalimemon/Gwt-Presentations"&gt;http://github.com/nabeelalimemon/Gwt-Presentations&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Have fun building your presentations.&lt;br /&gt;&lt;br /&gt;Update 1: To actually use this project to build your presentation slides yourself, you can follow the &lt;a href="http://wiki.github.com/nabeelalimemon/Gwt-Presentations/"&gt;wiki&lt;/a&gt;&amp;nbsp;I've created for my GitHub's Gwt-Presentation repo&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5403612535047815315-504395073982198828?l=nabeelalimemon.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nabeelalimemon.blogspot.com/feeds/504395073982198828/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/06/gwt-coded-presentations.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/504395073982198828'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/504395073982198828'/><link rel='alternate' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/06/gwt-coded-presentations.html' title='Gwt-coded Presentations'/><author><name>Nabeel Ali Memon</name><uri>http://www.blogger.com/profile/02353619277056408053</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5403612535047815315.post-7691697015208770006</id><published>2010-05-18T01:51:00.005+05:00</published><updated>2010-06-14T10:43:35.402+05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Test'/><category scheme='http://www.blogger.com/atom/ns#' term='Integration'/><category scheme='http://www.blogger.com/atom/ns#' term='Unit'/><category scheme='http://www.blogger.com/atom/ns#' term='TestNG'/><title type='text'>Unit and Integration Testing with TestNG</title><content type='html'>I am a big fan of developer testing. You begin to realize the real benefits of testing, six months down the road (or maybe a year) when your code-base starts growing, your project has more features than before and suddenly you come across a bug. You write your patch and start thinking how would you test that patch and make sure that:&lt;br /&gt;&lt;br /&gt;I) It actually solves the issue&lt;br /&gt;II) It doesn't shake already working features&lt;br /&gt;III) It doesn't, by any chance, introduce a new bug&lt;br /&gt;&lt;br /&gt;Then you realize that proper testing would've helped you a lot. Your test code is as important as your production code. The moment you start ignoring testing is the moment your code-base starts turning into a nightmare.&lt;br /&gt;&lt;br /&gt;Some people even push testing to the levels where it may help design good API's. Yes, I am talking about this&amp;nbsp;&lt;a href="http://tedyoung.blogsome.com/2010/02/11/my-first-screencast-writing-fluent-apis-in-java-episode-1-comparing-dates/"&gt;blog post of Ted Young&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Good frameworks that realize that the client code should be easy-to-test provide good unit/integration testing support. Let's see how Spring 3 provides better support for unit/integration testing while maintaining great flexibility for clients at the same time.&lt;br /&gt;&lt;br /&gt;Let's go back to our &lt;a href="http://code.google.com/p/spring3-hibernate-integration/"&gt;Spring 3 &amp;amp; Hibernate integration&lt;/a&gt;&amp;nbsp;project and write unit/integration tests for it.&lt;br /&gt;&lt;br /&gt;First off, we'll have to change our pom.xml&amp;nbsp;a bit to remove non-Spring-3 library dependencies in our project's dependency graph. For your convenience, here's the updated version of&amp;nbsp;&lt;a href="http://code.google.com/p/spring3-hibernate-integration/source/browse/trunk/pom.xml"&gt;pom.xml&lt;/a&gt;&amp;nbsp;(updated on rev: 5)&lt;br /&gt;&lt;br /&gt;You may notice that I've added TestNG 5.12.1 dependency with sure-fire plugin to the pom.xml. Yes, instead of JUnit, we'll use a far superior and flexible testing framework called TestNG.&lt;br /&gt;&lt;br /&gt;Tests should be kept as close to their target sources as possible. Luckily, in Java we have package semantics. Which means we can even test package-private methods which are for internal use and which we don't expose to the clients.&lt;br /&gt;&lt;br /&gt;After creating test folder following maven convention, we create packages inside that with the same names as our source packages are.&lt;br /&gt;&lt;br /&gt;Before we begin writing test cases, make sure you've created 'testng.xml' under 'test/java/resources' which will work as our tests' configuration file. Your testng.xml should contain all necessary information regarding test-run configuration and package information where your tests reside.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"&amp;gt;&lt;br /&gt;&amp;lt;suite thread-count="10" verbose="1" name="SpringHibernateIntegration-suite" annotations="JDK" parallel="methods"&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!--base defaults which i'll be passing to my test methods--&amp;gt;&lt;br /&gt;&amp;lt;parameter name="firstName" value="Nabeel"/&amp;gt;&lt;br /&gt;&amp;lt;parameter name="lastName" value="Memon"/&amp;gt;&lt;br /&gt;&amp;lt;parameter name="emailAddress" value="nabeelalimemon@gmail.com"/&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!--view names that return from UserController methods--&amp;gt;&lt;br /&gt;&amp;lt;parameter name="getUsers" value="users"/&amp;gt;&lt;br /&gt;&amp;lt;parameter name="getUser" value="userDetails"/&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;test name="integration-tests"&amp;gt;&lt;br /&gt;&amp;lt;packages&amp;gt;&lt;br /&gt;&amp;lt;package name="com.springhibernate.integration.model"/&amp;gt;&lt;br /&gt;&amp;lt;package name="com.springhibernate.integration.repository"/&amp;gt;&lt;br /&gt;&amp;lt;package name="com.springhibernate.integration.web.controllers"/&amp;gt;&lt;br /&gt;&amp;lt;/packages&amp;gt;&lt;br /&gt;&amp;lt;/test&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/suite&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;Let's test our business Entity first which is 'User'.&lt;br /&gt;&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration.model;&lt;br /&gt;&lt;br /&gt;import org.testng.annotations.Parameters;&lt;br /&gt;import org.testng.annotations.Test;&lt;br /&gt;&lt;br /&gt;import static org.testng.Assert.assertEquals;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author Nabeel Ali Memon&lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;@Test&lt;br /&gt;public class UserTest {&lt;br /&gt;  @Test&lt;br /&gt;  @Parameters({"firstName", "lastName", "emailAddress"})&lt;br /&gt;  public void setAndGetAttrs(String firstName, String lastName, String emailAddress) {&lt;br /&gt;    User user = new User();&lt;br /&gt;    user.setFirstName(firstName);&lt;br /&gt;    user.setLastName(lastName);&lt;br /&gt;    user.setEmail(emailAddress);&lt;br /&gt;&lt;br /&gt;    assertEquals(user.getFirstName(), firstName, "Should get first name that was set");&lt;br /&gt;    assertEquals(user.getLastName(), lastName, "Should get last name that was set");&lt;br /&gt;    assertEquals(user.getEmail(), emailAddress, "Should get email address that was set");&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;Notice that although business entities are often trivial to test, like in this case i've just written a test for getters/setters which may look trivial. But trust me, it helps when you try to start relying on your test suite.&lt;br /&gt;&lt;br /&gt;Let's move towards our repository layer where, perhaps, the most critical part of any application resides. We know them as transactions which are quite sensitive, must obey business complications and yet they must be efficient and fail-safe. In one of my previous blog posts&amp;nbsp;&lt;a href="http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part_13.html"&gt;I had explained&lt;/a&gt;&amp;nbsp;how peacefully we can configure transactional operations using the flexibility of Spring 3 and AOP. Now we'll see how much flexibility does Spring 3 provide on the same par to test those transactions. We'll write integration tests for our repository and will use same database to execute tests(which will rollback after every test execution of course). &lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration.repository;&lt;br /&gt;&lt;br /&gt;import com.springhibernate.integration.model.User;&lt;br /&gt;import org.springframework.beans.factory.annotation.Autowired;&lt;br /&gt;import org.springframework.test.context.ContextConfiguration;&lt;br /&gt;import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;&lt;br /&gt;import org.springframework.transaction.annotation.Transactional;&lt;br /&gt;import org.testng.Assert;&lt;br /&gt;import org.testng.annotations.BeforeClass;&lt;br /&gt;import org.testng.annotations.Parameters;&lt;br /&gt;import org.testng.annotations.Test;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author Nabeel Ali Memon&lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;@ContextConfiguration(locations = {"classpath:/META-INF/spring/integration-data.xml"})&lt;br /&gt;public class UserBaseTest extends AbstractTransactionalTestNGSpringContextTests {&lt;br /&gt;  @Autowired&lt;br /&gt;  private UserBase userRepository;&lt;br /&gt;&lt;br /&gt;  private User user;&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * Preparing test data which will be initialized only once for all @Test methods of this class&lt;br /&gt;   */&lt;br /&gt;  @BeforeClass&lt;br /&gt;  @Parameters({"firstName", "lastName", "emailAddress"})&lt;br /&gt;  public void init(String firstName, String lastName, String emailAddress) {&lt;br /&gt;    user = new User();&lt;br /&gt;    user.setFirstName(firstName);&lt;br /&gt;    user.setLastName(lastName);&lt;br /&gt;    user.setEmail(emailAddress);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * Transactional operation which will be rolled back by Spring after the test method runs&lt;br /&gt;   */&lt;br /&gt;  @Test&lt;br /&gt;  @Transactional&lt;br /&gt;  public void addAndGetUser() {&lt;br /&gt;    int actualUsers = userRepository.getUsers().size();&lt;br /&gt;    userRepository.addUser(user);&lt;br /&gt;    int incrementedUsers = userRepository.getUsers().size();&lt;br /&gt;    Assert.assertNotNull(user.getId(), "If user is persisted it must have been assigned an id");&lt;br /&gt;    Assert.assertEquals(incrementedUsers, actualUsers + 1, "After adding 1 user, total users' count must increment by 1");&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;It is due to Spring's provision of TestContext framework which handles caching and context management and which in turn makes your test executions really fast. You may notice that here we've extended Spring's TestNG Transactional TestContext support [abtract] class that Spring provides to perform integration testing through TestNG with transaction support.&lt;br /&gt;&lt;br /&gt;Going towards the end of this post, we have Spring web MVC controllers to test. Even for Controllers, Spring provides it's handy mock objects which can be used to write unit tests. The mix the using EasyMock for mocking up repository bean makes it even more fun. &lt;br /&gt;&lt;br /&gt;Now we can easily mock up our 'UserBase' repository bean, instantiate our controller and directly call methods on them. This way we'll be able to test our controller's method response quite easily. But, what about testing the RequestMapping and friends. Well, let's see Spring provided mock objects and EasyMock in action.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration.web.controllers;&lt;br /&gt;&lt;br /&gt;import com.springhibernate.integration.model.User;&lt;br /&gt;import com.springhibernate.integration.repository.UserBase;&lt;br /&gt;import org.easymock.EasyMock;&lt;br /&gt;import org.springframework.mock.web.MockHttpServletRequest;&lt;br /&gt;import org.springframework.mock.web.MockHttpServletResponse;&lt;br /&gt;import org.springframework.web.servlet.HandlerMapping;&lt;br /&gt;import org.springframework.web.servlet.ModelAndView;&lt;br /&gt;import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;&lt;br /&gt;import org.testng.Assert;&lt;br /&gt;import org.testng.annotations.BeforeMethod;&lt;br /&gt;import org.testng.annotations.Parameters;&lt;br /&gt;import org.testng.annotations.Test;&lt;br /&gt;&lt;br /&gt;import java.util.ArrayList;&lt;br /&gt;import java.util.HashMap;&lt;br /&gt;import java.util.List;&lt;br /&gt;import java.util.Map;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author Nabeel Ali Memon&lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;@Test&lt;br /&gt;public class UserControllerTest {&lt;br /&gt;  private MockHttpServletRequest request;&lt;br /&gt;  private MockHttpServletResponse response;&lt;br /&gt;  private UserController userController;&lt;br /&gt;  private AnnotationMethodHandlerAdapter methodHandlerAdapter;&lt;br /&gt;  private UserBase userRepositoryMock;&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * Initialize before every individual test method&lt;br /&gt;   */&lt;br /&gt;  @BeforeMethod&lt;br /&gt;  public void init() {&lt;br /&gt;    request = new MockHttpServletRequest();&lt;br /&gt;    response = new MockHttpServletResponse();&lt;br /&gt;    methodHandlerAdapter = new AnnotationMethodHandlerAdapter();&lt;br /&gt;    userRepositoryMock = EasyMock.createStrictMock(UserBase.class);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Test(alwaysRun = true)&lt;br /&gt;  @Parameters({"getUsers"})&lt;br /&gt;  public void getAllUsers(String usersPage) throws Exception {&lt;br /&gt;    List&lt;user&gt; users = new ArrayList&lt;user&gt;();&lt;br /&gt;    request.setRequestURI("/integration/users");&lt;br /&gt;    request.setMethod("GET");&lt;br /&gt;    EasyMock.expect(userRepositoryMock.getUsers()).andReturn(users);&lt;br /&gt;    EasyMock.replay(userRepositoryMock);&lt;br /&gt;    userController = new UserController(userRepositoryMock);&lt;br /&gt;    ModelAndView modelAndView = methodHandlerAdapter.handle(request, response, userController);&lt;br /&gt;    Assert.assertEquals(modelAndView.getViewName(), usersPage, "returned view name should be " + usersPage);&lt;br /&gt;    EasyMock.verify(userRepositoryMock);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * Let this method run after the previous method is done. It keeps you from thread-safety&lt;br /&gt;   * issues while using mock-ups.&lt;br /&gt;   */&lt;br /&gt;  @Test(dependsOnMethods = {"getAllUsers"}, alwaysRun = true)&lt;br /&gt;  @Parameters({"getUser"})&lt;br /&gt;  public void getSingleUser(String userDetailsPage) throws Exception {&lt;br /&gt;    request.setRequestURI("/integration/users/{id}");&lt;br /&gt;    request.setMethod("GET");&lt;br /&gt;    User user = new User();&lt;br /&gt;    Long userId = new Long(1);&lt;br /&gt;    Map&lt;string, string=""&gt; pathVariables = new HashMap&lt;string, string=""&gt;();&lt;br /&gt;    pathVariables.put("id", String.valueOf(userId));&lt;br /&gt;    request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, pathVariables);&lt;br /&gt;    EasyMock.expect(userRepositoryMock.getUser(userId)).andReturn(user).anyTimes();&lt;br /&gt;    EasyMock.replay(userRepositoryMock);&lt;br /&gt;    userController = new UserController(userRepositoryMock);&lt;br /&gt;    ModelAndView modelAndView = methodHandlerAdapter.handle(request, response, userController);&lt;br /&gt;    Assert.assertEquals(modelAndView.getViewName(), userDetailsPage, "returned view name should be " + userDetailsPage);&lt;br /&gt;    EasyMock.verify(userRepositoryMock);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/string,&gt;&lt;/string,&gt;&lt;/user&gt;&lt;/user&gt;&lt;/code&gt;&lt;/pre&gt;Note that i've carefully used test configuration options provided by TestNG framework in order to achieve cleaner, reliable and efficient tests. Although a good support for unit-testing becomes available when you introduce 'Dependency Injection' to your application design, but frameworks like Spring take it a step further and make it much cleaner and fun to write.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5403612535047815315-7691697015208770006?l=nabeelalimemon.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nabeelalimemon.blogspot.com/feeds/7691697015208770006/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/05/unit-and-integration-testing-with.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/7691697015208770006'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/7691697015208770006'/><link rel='alternate' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/05/unit-and-integration-testing-with.html' title='Unit and Integration Testing with TestNG'/><author><name>Nabeel Ali Memon</name><uri>http://www.blogger.com/profile/02353619277056408053</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5403612535047815315.post-978432292263816882</id><published>2010-05-13T23:49:00.010+05:00</published><updated>2010-06-14T10:43:54.550+05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Spring'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate'/><title type='text'>Spring 3 integrated with Hibernate Part-C</title><content type='html'>After going through &lt;a href="http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part_12.html"&gt;Part-B&lt;/a&gt;&amp;nbsp;of this tutorial series, you must have a working console application built on Spring 3 and Hibernate and by now you must have got a good idea of how Spring can manage your database transactions by encapsulating persistence-layer based transactions behind the curtains. Yes, behind the scenes Spring delegates transactional handling to [in our case] Hibernate and exposes an easy-to-use transaction facade for us. Since Spring has been in such a widespread use that if you follow old-school DAO pattern to encapsulate Hibernate POJO's then you don't even need to provide transaction details, instead you just extend one of the Spring provided DAO templates (HibernateTemplate in our case), override the CRUD methods and Spring will handle transaction details internally. But it poses two serious drawbacks of vendor lock-in and tight-coupling.&lt;br /&gt;&lt;br /&gt;Let's move forward towards turning our project into a web application but hey what about Aspect-oriented programming stuff? I'm sure you must have heard a lot about AOP and maybe some of you know just how to get around it. In any case I assume that you understand what is:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Aspect:&lt;/b&gt; &lt;i&gt;A concern that cuts across multiple classes. For example Transaction, Logging, Authentication etcetera.&lt;/i&gt;&lt;br /&gt;&lt;b&gt;Join Point:&lt;/b&gt; &lt;i&gt;A point during the program's execution. In Spring, only method execution represents a Join Point.&lt;/i&gt;&lt;br /&gt;&lt;b&gt;Advice:&lt;/b&gt; &lt;i&gt;An action taken by an Aspect on a Join Point. That Advice might be executed "before", "after", "after-return" or "around" that Join Point. In Spring, an Advice executes as an Interceptor.&lt;/i&gt;&lt;br /&gt;&lt;b&gt;Pointcut:&lt;/b&gt; &lt;i&gt;An expression that when matches with a Join Point, the associated Advice is executed. Spring uses AspectJ's expression language to define Pointcuts.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;Instead of going the old-school way of following schema-based approach to declare aspects in Spring configuration .xml file, let's use Spring's powerful AOP support annotations.&lt;br /&gt;&lt;br /&gt;You may observe that we haven't logged our transactional methods yet which is commonly followed practice. This functionality can be flexibly achieved using AOP. So let's start some coding.&lt;br /&gt;&lt;br /&gt;1: To enable AspectJ support to this application you need to declare following inside 'META-INF/spring/integration-data.xml'&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;aop:aspect-autoproxy/&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;2: Under 'src/main/java/com/springhibernate/integration' create a package named 'aspects'.&lt;br /&gt;3: Inside 'aspects' package, create a class 'LoggingAspect.java' with proper annotations on class and it's methods that are required for an AOP Advice to execute in a desirable manner.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration.aspects;&lt;br /&gt;&lt;br /&gt;import org.aspectj.lang.annotation.*;&lt;br /&gt;import org.springframework.stereotype.Component;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author Nabeel Ali Memon&lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;@Component&lt;br /&gt;@Aspect&lt;br /&gt;public class LoggingAspect {&lt;br /&gt;  //Pointcut definition for all repository transactions that get entities&lt;br /&gt;  @Pointcut("execution(* com.springhibernate.integration.repository.*.get*(..))")&lt;br /&gt;  public void getterTransaction() {}&lt;br /&gt;&lt;br /&gt;  //Pointcut definition for all repository transactions that add entities&lt;br /&gt;  @Pointcut("execution(* com.springhibernate.integration.repository.*.add*(..))")&lt;br /&gt;  public void adderTransaction() {}&lt;br /&gt;&lt;br /&gt;  //For common Advice on both Pointcuts we combine them to make a single Pointcut&lt;br /&gt;  @Pointcut("adderTransaction() || getterTransaction()")&lt;br /&gt;  public void adderOrGetterTransaction() {}&lt;br /&gt;&lt;br /&gt;  //Advice that executes before an Adder or Getter Transaction Join Point is called&lt;br /&gt;  @Before("adderOrGetterTransaction()")&lt;br /&gt;  public void beforeTransaction() {&lt;br /&gt;    System.out.println("------------------------------------");&lt;br /&gt;    System.out.println("--------Beginning transaction-------");&lt;br /&gt;    System.out.println("------------------------------------");&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @AfterThrowing(pointcut = "adderOrGetterTransaction()", throwing = "throwable")&lt;br /&gt;  public void adderOrGetterThrewException(Throwable throwable) {&lt;br /&gt;    throw new RuntimeException("Transaction Unsuccessful. "+throwable.getMessage());&lt;br /&gt;  }&lt;br /&gt;  //Advice that executes after an Adder Transaction Join Point is executed&lt;br /&gt;  @After("adderTransaction()")&lt;br /&gt;  public void afterAdderTransaction() {&lt;br /&gt;    System.out.println("-------Ending Adder Transaction-----");&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  //Advice that executes after a Getter Transaction Join Point is executed&lt;br /&gt;  @AfterReturning(pointcut = "getterTransaction()", returning = "retVal")&lt;br /&gt;  public void afterGetterTransaction(Object retVal) {&lt;br /&gt;    System.out.println("Transaction returned value: "+ retVal.toString());&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;Note: Again, you can read my comments inside code to clearly understand which annotation is doing what. You can do many useful things with AOP Advices, but, just to make it more easy-to-understand I rather did simple logging.&lt;br /&gt;&lt;br /&gt;4: To let Spring container auto-detect and initialize the bean that we just created, declare the following in 'META-INF/spring/integration-date.xml'&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;context:component-scan&amp;nbsp;base package="com.springhibernate.integration.aspects"&amp;nbsp;/&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;You can go back to 'App.java' and execute it as is and read the console output to see AOP in action.&lt;br /&gt;&lt;br /&gt;We'r not gonna log every detail using AOP, that was just for transactional stuff. Let's turn to the widely used log4j logging. The dependency declaration, classpath scope everything is already in place inside your 'pom.xml'. All we have to do is to create a file 'log4j.properties' under 'META-INF/properties'&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;log4j.appender.stdout=org.apache.log4j.ConsoleAppender&lt;br /&gt;log4j.rootLogger=DEBUG, stdout, R&lt;br /&gt;log4j.appender.R.File=application.log&lt;br /&gt;log4j.appender.R.MaxFileSize=100KB&lt;br /&gt;log4j.appender.R.layout=org.apache.log4j.PatternLayout&lt;br /&gt;log4j.appender.R.MaxBackupIndex=1&lt;br /&gt;log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n&lt;br /&gt;log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n&lt;br /&gt;log4j.appender.stdout.layout=org.apache.log4j.PatternLayout&lt;br /&gt;log4j.appender.R=org.apache.log4j.RollingFileAppender&lt;br /&gt;&lt;br /&gt;log4j.logger.org.hibernate.SQL=debug&lt;br /&gt;log4j.logger.org.hibernate.tool.hbm2ddl=debug&lt;br /&gt;log4j.logger.org.hibernate.hql=debug&lt;br /&gt;log4j.logger.org.hibernate.transaction=debug&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Of course it's a matter of convenience to configure logging that matches your choices.&lt;br /&gt;&lt;br /&gt;Since we have an application engine in place and working, let's actually turn it into a web application. We'll be using widely adopted MVC pattern for our web layer provided by Spring MVC. Although we'll just scratch the surface of what Spring MVC has to offer us with the release of Spring 3, but you'll get an idea of how flexible it is compared to frameworks like Struts and JSF etcetera. Detailed coverage of Spring MVC is an interesting topic i'll keep for my next blog post.&lt;br /&gt;&lt;br /&gt;1: Create a folder named 'spring' under 'src/main/webapp/WEB-INF'&lt;br /&gt;2: To use Spring MVC we need to have some configuration declared in our Spring configuration .xml file. We'll create a separate file named 'integration-mvc.xml' inside 'spring' folder that we just created.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;?xml&amp;nbsp;version="1.0"&amp;nbsp;encoding="UTF-8"?&amp;gt;  &lt;br /&gt;&amp;lt;beans&amp;nbsp;xmlns="http://www.springframework.org/schema/beans"  &lt;br /&gt;xmlns:context="http://www.springframework.org/schema/context"  &lt;br /&gt;xmlns:mvc="http://www.springframework.org/schema/mvc"  &lt;br /&gt;xmlns:p="http://www.springframework.org/schema/p"  &lt;br /&gt;xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  &lt;br /&gt;xsi:schemaLocation="http://www.springframework.org/schema/beans  &lt;br /&gt;http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  &lt;br /&gt;http://www.springframework.org/schema/context  &lt;br /&gt;http://www.springframework.org/schema/context/spring-context-3.0.xsd  &lt;br /&gt;http://www.springframework.org/schema/mvc&amp;nbsp;http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"&amp;gt;  &lt;br /&gt;&lt;br /&gt;&amp;lt;!--controllers&amp;nbsp;are&amp;nbsp;autodetected&amp;nbsp;pojo's&amp;nbsp;annotated&amp;nbsp;with&amp;nbsp;@Controller--&amp;gt;  &lt;br /&gt;&amp;lt;context:component-scan&amp;nbsp;base-package="com.springhibernate.integration.web.controllers"&amp;nbsp;use-default-filters="false"&amp;gt;  &lt;br /&gt;&amp;lt;context:include-filter&amp;nbsp;type="annotation"&amp;nbsp;expression="org.springframework.stereotype.Controller"/&amp;gt;  &lt;br /&gt;&amp;lt;/context:component-scan&amp;gt;  &lt;br /&gt;&lt;br /&gt;&amp;lt;!--support&amp;nbsp;for&amp;nbsp;@Controller&amp;nbsp;mvc&amp;nbsp;request&amp;nbsp;mapping.&amp;nbsp;also&amp;nbsp;registers&amp;nbsp;formatters&amp;nbsp;and&amp;nbsp;validators&amp;nbsp;for&amp;nbsp;use&amp;nbsp;across&amp;nbsp;@Controller--&amp;gt;  &lt;br /&gt;&amp;lt;mvc:annotation-driven/&amp;gt;  &lt;br /&gt;&lt;br /&gt;&amp;lt;!--select&amp;nbsp;static&amp;nbsp;view&amp;nbsp;for&amp;nbsp;rendering&amp;nbsp;without&amp;nbsp;going&amp;nbsp;through&amp;nbsp;@Controller--&amp;gt;  &lt;br /&gt;&amp;lt;mvc:view-controller&amp;nbsp;path="/index"&amp;nbsp;view-name="index"/&amp;gt;  &lt;br /&gt;&lt;br /&gt;&amp;lt;!--inside&amp;nbsp;controllers&amp;nbsp;you&amp;nbsp;don't&amp;nbsp;need&amp;nbsp;to&amp;nbsp;worry&amp;nbsp;about&amp;nbsp;where&amp;nbsp;your&amp;nbsp;jsp&amp;nbsp;is&amp;nbsp;located--&amp;gt;  &lt;br /&gt;&amp;lt;bean&amp;nbsp;id="viewResolver"&amp;nbsp;class="org.springframework.web.servlet.view.UrlBasedViewResolver"&amp;gt;  &lt;br /&gt;&amp;lt;property&amp;nbsp;name="viewClass"&amp;nbsp;value="org.springframework.web.servlet.view.JstlView"/&amp;gt;  &lt;br /&gt;&amp;lt;property&amp;nbsp;name="prefix"&amp;nbsp;value="/WEB-INF/views/"/&amp;gt;  &lt;br /&gt;&amp;lt;property&amp;nbsp;name="suffix"&amp;nbsp;value=".jsp"/&amp;gt;  &lt;br /&gt;&amp;lt;/bean&amp;gt;  &lt;br /&gt;&lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;3: Create subsequent packages named 'web/controllers' under '/src/main/java/com/springhibernate/integration'&lt;br /&gt;4: In 'controllers' package, create a Spring MVC controller named 'User'Controller'. We'll use this controller to respond to web requests on our User entity.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration.web.controllers;&lt;br /&gt;&lt;br /&gt;import com.springhibernate.integration.model.User;&lt;br /&gt;import com.springhibernate.integration.repository.UserBase;&lt;br /&gt;import org.springframework.beans.factory.annotation.Autowired;&lt;br /&gt;import org.springframework.stereotype.Controller;&lt;br /&gt;import org.springframework.web.bind.annotation.PathVariable;&lt;br /&gt;import org.springframework.web.bind.annotation.RequestMapping;&lt;br /&gt;import org.springframework.web.bind.annotation.RequestMethod;&lt;br /&gt;import org.springframework.web.servlet.ModelAndView;&lt;br /&gt;&lt;br /&gt;import java.util.List;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author Nabeel Ali Memon&lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * This annotation makes it a Spring MVC controller.&lt;br /&gt; * No need to extend any abstract controller like old Spring way&lt;br /&gt; */&lt;br /&gt;@Controller&lt;br /&gt;/**&lt;br /&gt; * Spring MVC 3 supports RESTful URL's out of the box.&lt;br /&gt; * Every request on 'integration' resource will be handled by this controller&lt;br /&gt; */&lt;br /&gt;@RequestMapping("/integration/*")&lt;br /&gt;public class UserController {&lt;br /&gt;  private UserBase usersRepository;&lt;br /&gt;&lt;br /&gt;  //Injecting a repository bean to talk to database&lt;br /&gt;  @Autowired&lt;br /&gt;  public UserController(UserBase usersRepository) {&lt;br /&gt;    this.usersRepository = usersRepository;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * List all the users and display "users.jsp" page.&lt;br /&gt;   * The location and mime-type of "users.jsp" will be resolved by Spring container's "viewResolver" bean&lt;br /&gt;   * that declared in "integration-mvc.xml"&lt;br /&gt;   */&lt;br /&gt;  @RequestMapping(value = "users", method = RequestMethod.GET)&lt;br /&gt;  public ModelAndView getUsers() {&lt;br /&gt;    List&lt;user&gt; users = usersRepository.getUsers();&lt;br /&gt;    ModelAndView modelAndView = new ModelAndView("users");&lt;br /&gt;    modelAndView.addObject("users", users);&lt;br /&gt;    return modelAndView;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  /**&lt;br /&gt;   * To get a specific User by it's user-id RESTfully.&lt;br /&gt;   * Notice how easily you can bind a RESTful request parameter to a controllers method parameter&lt;br /&gt;   * using @PathVariable&lt;br /&gt;   */&lt;br /&gt;  @RequestMapping(value = "users/{id}", method = RequestMethod.GET)&lt;br /&gt;  public ModelAndView getUser(@PathVariable Long id) {&lt;br /&gt;    User user = usersRepository.getUser(id);&lt;br /&gt;    ModelAndView modelAndView = new ModelAndView("userDetails");&lt;br /&gt;    modelAndView.addObject("user", user);&lt;br /&gt;    return modelAndView;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/user&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;5: Create the jsp pages 'users.jsp' and 'userDetails.jsp' in 'views' folder which you'll create under 'webapp/WEB-INF'&lt;br /&gt;Users.jsp&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;%@&amp;nbsp;page&amp;nbsp;contentType="text/html;charset=UTF-8"&amp;nbsp;language="java"&amp;nbsp;%&amp;gt;&lt;br /&gt;&amp;lt;%@&amp;nbsp;page&amp;nbsp;isELIgnored="false"&amp;nbsp;%&amp;gt;&lt;br /&gt;&amp;lt;%@&amp;nbsp;taglib&amp;nbsp;prefix="c"&amp;nbsp;uri="http://java.sun.com/jsp/jstl/core"&amp;nbsp;%&amp;gt;&lt;br /&gt;&amp;lt;%@&amp;nbsp;taglib&amp;nbsp;prefix="fn"&amp;nbsp;uri="http://java.sun.com/jsp/jstl/functions"&amp;nbsp;%&amp;gt;&lt;br /&gt;&amp;lt;html&amp;gt;&lt;br /&gt;&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;All&amp;nbsp;Users&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;&amp;lt;body&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;h2&amp;gt;Total&amp;nbsp;Users:&amp;nbsp;&amp;lt;c:out&amp;nbsp;value="${fn:length(users)}"/&amp;gt;&amp;nbsp;&amp;lt;/h2&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&amp;lt;c:forEach&amp;nbsp;var="user"&amp;nbsp;items="${users}"&amp;gt;&lt;br /&gt;&amp;lt;h3&amp;gt;User's&amp;nbsp;Details:&amp;lt;/h3&amp;gt;&lt;br /&gt;&lt;br /&gt;First&amp;nbsp;Name:&amp;nbsp;&amp;lt;c:out&amp;nbsp;value="${user.firstName}"/&amp;gt;&lt;br /&gt;Last&amp;nbsp;Name:&amp;nbsp;&amp;lt;c:out&amp;nbsp;value="${user.lastName}"/&amp;gt;&amp;nbsp;&lt;br /&gt;Email&amp;nbsp;Address:&amp;nbsp;&amp;lt;c:out&amp;nbsp;value="${user.email}"/&amp;gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;&amp;lt;/c:forEach&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/body&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;UserDetails.jsp&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;%@&amp;nbsp;page&amp;nbsp;contentType="text/html;charset=UTF-8"&amp;nbsp;language="java"&amp;nbsp;%&amp;gt;&lt;br /&gt;&amp;lt;%@&amp;nbsp;page&amp;nbsp;isELIgnored="false"&amp;nbsp;%&amp;gt;&lt;br /&gt;&amp;lt;%@&amp;nbsp;taglib&amp;nbsp;prefix="c"&amp;nbsp;uri="http://java.sun.com/jsp/jstl/core"&amp;nbsp;%&amp;gt;&lt;br /&gt;&amp;lt;html&amp;gt;&lt;br /&gt;&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;User&amp;nbsp;Details&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;body&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;h3&amp;gt;User's&amp;nbsp;Details:&amp;lt;/h3&amp;gt;&lt;br /&gt;&lt;br /&gt;First&amp;nbsp;Name:&amp;nbsp;&amp;lt;c:out&amp;nbsp;value="${user.firstName}"/&amp;gt;&lt;br /&gt;Last&amp;nbsp;Name:&amp;nbsp;&amp;lt;c:out&amp;nbsp;value="${user.lastName}"/&amp;gt;&amp;nbsp;&lt;br /&gt;Email&amp;nbsp;Address:&amp;nbsp;&amp;lt;c:out&amp;nbsp;value="${user.email}"/&amp;gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;&amp;lt;/body&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;6: To deploy this app on a web container (Jetty in our case) we need a deployment descriptor and since we'r using Spring container and Log4j, we need to provide additional context configuration in our 'web.xml'&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;!DOCTYPE&amp;nbsp;web-app&amp;nbsp;PUBLIC&lt;br /&gt;"-//Sun&amp;nbsp;Microsystems,&amp;nbsp;Inc.//DTD&amp;nbsp;Web&amp;nbsp;Application&amp;nbsp;2.3//EN"&lt;br /&gt;"http://java.sun.com/dtd/web-app_2_3.dtd"&amp;nbsp;&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;web-app&amp;gt;&lt;br /&gt;&amp;lt;display-name&amp;gt;Archetype&amp;nbsp;Created&amp;nbsp;Web&amp;nbsp;Application&amp;lt;/display-name&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;context-param&amp;gt;&lt;br /&gt;&amp;lt;param-name&amp;gt;log4jConfigLocation&amp;lt;/param-name&amp;gt;&lt;br /&gt;&amp;lt;param-value&amp;gt;classpath:META-INF/properties/log4j.properties&amp;lt;/param-value&amp;gt;&lt;br /&gt;&amp;lt;/context-param&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;listener&amp;gt;&lt;br /&gt;&amp;lt;listener-class&amp;gt;org.springframework.web.util.Log4jConfigListener&amp;lt;/listener-class&amp;gt;&lt;br /&gt;&amp;lt;/listener&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!--All&amp;nbsp;spring&amp;nbsp;configuration&amp;nbsp;files&amp;nbsp;need&amp;nbsp;to&amp;nbsp;be&amp;nbsp;loaded&amp;nbsp;in&amp;nbsp;context.&amp;nbsp;Although&amp;nbsp;we&amp;nbsp;have&amp;nbsp;single&amp;nbsp;file&amp;nbsp;but&lt;br /&gt;with&amp;nbsp;the&amp;nbsp;growing&amp;nbsp;configuration&amp;nbsp;stuff&amp;nbsp;we&amp;nbsp;need&amp;nbsp;to&amp;nbsp;break&amp;nbsp;down&amp;nbsp;configuration&amp;nbsp;files&amp;nbsp;too--&amp;gt;&lt;br /&gt;&amp;lt;context-param&amp;gt;&lt;br /&gt;&amp;lt;param-name&amp;gt;contextConfigLocation&amp;lt;/param-name&amp;gt;&lt;br /&gt;&amp;lt;param-value&amp;gt;classpath*:META-INF/spring/integration-*.xml&amp;lt;/param-value&amp;gt;&lt;br /&gt;&amp;lt;/context-param&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;listener&amp;gt;&lt;br /&gt;&amp;lt;listener-class&amp;gt;org.springframework.web.context.ContextLoaderListener&amp;lt;/listener-class&amp;gt;&lt;br /&gt;&amp;lt;/listener&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;servlet&amp;gt;&lt;br /&gt;&amp;lt;!--Spring's&amp;nbsp;front&amp;nbsp;controller&amp;nbsp;or&amp;nbsp;dispatcher&amp;nbsp;which&amp;nbsp;will&amp;nbsp;be&amp;nbsp;responsible&amp;nbsp;to&amp;nbsp;handle&amp;nbsp;every&amp;nbsp;web&amp;nbsp;request&lt;br /&gt;and&amp;nbsp;dispatch&amp;nbsp;it&amp;nbsp;to&amp;nbsp;a&amp;nbsp;specific&amp;nbsp;web&amp;nbsp;controller--&amp;gt;&lt;br /&gt;&amp;lt;servlet-name&amp;gt;integration&amp;lt;/servlet-name&amp;gt;&lt;br /&gt;&amp;lt;servlet-class&amp;gt;org.springframework.web.servlet.DispatcherServlet&amp;lt;/servlet-class&amp;gt;&lt;br /&gt;&amp;lt;load-on-startup&amp;gt;1&amp;lt;/load-on-startup&amp;gt;&lt;br /&gt;&amp;lt;init-param&amp;gt;&lt;br /&gt;&amp;lt;param-name&amp;gt;contextConfigLocation&amp;lt;/param-name&amp;gt;&lt;br /&gt;&amp;lt;param-value&amp;gt;/WEB-INF/spring/integration-mvc.xml&amp;lt;/param-value&amp;gt;&lt;br /&gt;&amp;lt;/init-param&amp;gt;&lt;br /&gt;&amp;lt;/servlet&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!--Let&amp;nbsp;every&amp;nbsp;request&amp;nbsp;be&amp;nbsp;handled&amp;nbsp;by&amp;nbsp;Spring's&amp;nbsp;Dispatcher&amp;nbsp;servlet&amp;nbsp;and&amp;nbsp;it'll&amp;nbsp;decide&amp;nbsp;which&amp;nbsp;web&amp;nbsp;controller&amp;nbsp;to&amp;nbsp;call&amp;nbsp;--&amp;gt;&lt;br /&gt;&amp;lt;!--based&amp;nbsp;on&amp;nbsp;@RequestMapping--&amp;gt;&lt;br /&gt;&amp;lt;servlet-mapping&amp;gt;&lt;br /&gt;&amp;lt;servlet-name&amp;gt;integration&amp;lt;/servlet-name&amp;gt;&lt;br /&gt;&amp;lt;url-pattern&amp;gt;/&amp;lt;/url-pattern&amp;gt;&lt;br /&gt;&amp;lt;/servlet-mapping&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;welcome-file-list&amp;gt;&lt;br /&gt;&amp;lt;welcome-file&amp;gt;&lt;br /&gt;index.jsp&lt;br /&gt;&amp;lt;/welcome-file&amp;gt;&lt;br /&gt;&amp;lt;/welcome-file-list&amp;gt;&lt;br /&gt;&amp;lt;/web-app&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;We have just created our web app based on Spring 3 and Hibernate using Maven 2. It's ready to be deployed and serve it's purpose. To deploy it, fire-up your command line and issue the following maven commands one by one:&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;mvn package&lt;br /&gt;mvn jetty:run&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;After you see a clean application boot sequence log on the console, you'r ready to visit your web app through your internet browser. Visit the following URL's in your browser, see the result data, read the console logs and code ahead.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;http://localhost:8080/spring-hibernate-webapp/integration/users&lt;br /&gt;http://localhost:8080/spring-hibernate-webapp/integration/users/1&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Although we haven't looked at various other features, some improved and some new, of Spring 3 yet. But I hope this tutorial series has given you a kickstart into the technologies we've used. More will be covered in depth into my future blog posts. So hang on.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5403612535047815315-978432292263816882?l=nabeelalimemon.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nabeelalimemon.blogspot.com/feeds/978432292263816882/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part_13.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/978432292263816882'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/978432292263816882'/><link rel='alternate' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part_13.html' title='Spring 3 integrated with Hibernate Part-C'/><author><name>Nabeel Ali Memon</name><uri>http://www.blogger.com/profile/02353619277056408053</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5403612535047815315.post-2996775559006793907</id><published>2010-05-12T22:41:00.020+05:00</published><updated>2010-06-14T10:44:02.553+05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Spring'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate'/><title type='text'>Spring 3 integrated with Hibernate Part-B</title><content type='html'>You must have reached this page after covering the first part of this tutorial series&amp;nbsp;&lt;a href="http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part.html"&gt;Spring 3 integrated with Hibernate part A&lt;/a&gt;. If not, then you need to go through that part prior to reading ahead.&lt;br /&gt;&lt;br /&gt;So let's move towards integrating Spring 3 into our project. We've already added Spring 3 dependency libraries' declarations in our pom.xml. You'll notice that we are using Spring framework version 3.0.2 which is the latest release of the framework to date. What we are going to do first is to create a Repository bean (to encapsulate Hibernate POJO's) and a Spring application context file. While using Spring, we'll prefer annotations over declarative approach which in turn will prove itself to be a much powerful and flexible approach and which is of course the whole point of this tutorial series.&lt;br /&gt;&lt;br /&gt;Let's actually get into it and start some coding now.&lt;br /&gt;&lt;br /&gt;1: Inside 'src/main/resources' create a folder named 'META-INF'.&lt;br /&gt;2: Inside 'META-INF' create two folders named 'spring' and 'properties' (we'll use 'spring' folder to place spring-specific configuration files and 'properties' folder for our database and log4j properties).&lt;br /&gt;3: Create a new file named 'database.properties' under 'META-INF/properties' which should have our database configuration.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;database.url=jdbc:mysql://localhost:3306/integration&lt;br /&gt;database.username=username&lt;br /&gt;database.password=password&lt;br /&gt;database.driverClassName=com.mysql.jdbc.Driver&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;code&gt;&lt;/code&gt;&lt;br /&gt;4: Create a new xml file named 'integration-data.xml' inside the folder 'META-INF/spring'. This file will contain our basic spring configuration to start with.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;?xml&amp;nbsp;version="1.0"&amp;nbsp;encoding="UTF-8"?&amp;gt;&lt;br /&gt;&amp;lt;beans&amp;nbsp;xmlns="http://www.springframework.org/schema/beans"&lt;br /&gt;xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&lt;br /&gt;xmlns:context="http://www.springframework.org/schema/context"&lt;br /&gt;xmlns:tx="http://www.springframework.org/schema/tx"&lt;br /&gt;xmlns:aop="http://www.springframework.org/schema/aop"&lt;br /&gt;xsi:schemaLocation="http://www.springframework.org/schema/beans&amp;nbsp;http://www.springframework.org/schema/beans/spring-beans.xsd &lt;br /&gt;http://www.springframework.org/schema/context&amp;nbsp;http://www.springframework.org/schema/context/spring-context.xsd &lt;br /&gt;http://www.springframework.org/schema/tx&amp;nbsp;http://www.springframework.org/schema/tx/spring-tx-3.0.xsd &lt;br /&gt;http://www.springframework.org/schema/aop&amp;nbsp;http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"&amp;gt; &lt;br /&gt;&lt;br /&gt;&amp;lt;!--You&amp;nbsp;don't&amp;nbsp;need&amp;nbsp;declarative&amp;nbsp;transactions.&amp;nbsp;By&amp;nbsp;declaring&amp;nbsp;&amp;lt;tx:annotation-driven...&amp;gt;&amp;nbsp;only,&amp;nbsp;you&amp;nbsp;just&amp;nbsp;annotate&amp;nbsp;your&amp;nbsp;repositories&amp;nbsp;with &lt;br /&gt;@Transaction--&amp;gt; &lt;br /&gt;&amp;lt;tx:annotation-driven&amp;nbsp;mode="aspectj"/&amp;gt; &lt;br /&gt;&lt;br /&gt;&amp;lt;bean&amp;nbsp;id="sessionFactory"&amp;nbsp;class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&amp;gt; &lt;br /&gt;&amp;lt;property&amp;nbsp;name="dataSource"&amp;nbsp;ref="dataSource"/&amp;gt; &lt;br /&gt;&amp;lt;property&amp;nbsp;name="hibernateProperties"&amp;gt; &lt;br /&gt;&amp;lt;props&amp;gt; &lt;br /&gt;&amp;lt;prop&amp;nbsp;key="dialect"&amp;gt;org.hibernate.dialect.MySQL5Dialect&amp;lt;/prop&amp;gt; &lt;br /&gt;&amp;lt;prop&amp;nbsp;key="show_sql"&amp;gt;true&amp;lt;/prop&amp;gt; &lt;br /&gt;&amp;lt;!--&amp;lt;prop&amp;nbsp;key="format_sql"&amp;gt;true&amp;lt;/prop&amp;gt;--&amp;gt; &lt;br /&gt;&amp;lt;/props&amp;gt; &lt;br /&gt;&amp;lt;/property&amp;gt; &lt;br /&gt;&amp;lt;property&amp;nbsp;name="mappingResources"&amp;gt; &lt;br /&gt;&amp;lt;list&amp;gt; &lt;br /&gt;&amp;lt;value&amp;gt;mappings/user.hbm.xml&amp;lt;/value&amp;gt; &lt;br /&gt;&amp;lt;/list&amp;gt; &lt;br /&gt;&amp;lt;/property&amp;gt; &lt;br /&gt;&amp;lt;/bean&amp;gt; &lt;br /&gt;&lt;br /&gt;&amp;lt;!--Put&amp;nbsp;your&amp;nbsp;often-changing&amp;nbsp;configuration&amp;nbsp;values&amp;nbsp;outside&amp;nbsp;spring&amp;nbsp;configuration&amp;nbsp;anywhere&amp;nbsp;and&amp;nbsp;let&amp;nbsp;spring&amp;nbsp;bring&amp;nbsp;those&amp;nbsp;changes&amp;nbsp;in--&amp;gt; &lt;br /&gt;&amp;lt;context:property-placeholder&amp;nbsp;location="classpath*:/META-INF/properties/*.properties"/&amp;gt; &lt;br /&gt;&lt;br /&gt;&amp;lt;bean&amp;nbsp;id="dataSource"&amp;nbsp;class="org.apache.commons.dbcp.BasicDataSource"&amp;gt; &lt;br /&gt;&amp;lt;property&amp;nbsp;name="driverClassName"&amp;nbsp;value="${database.driverClassName}"/&amp;gt; &lt;br /&gt;&amp;lt;property&amp;nbsp;name="url"&amp;nbsp;value="${database.url}"/&amp;gt; &lt;br /&gt;&amp;lt;property&amp;nbsp;name="username"&amp;nbsp;value="${database.username}"/&amp;gt; &lt;br /&gt;&amp;lt;property&amp;nbsp;name="password"&amp;nbsp;value="${database.password}"/&amp;gt; &lt;br /&gt;&amp;lt;/bean&amp;gt; &lt;br /&gt;&lt;br /&gt;&amp;lt;!--To&amp;nbsp;spring,&amp;nbsp;communication&amp;nbsp;with&amp;nbsp;a&amp;nbsp;database&amp;nbsp;must&amp;nbsp;take&amp;nbsp;place&amp;nbsp;in&amp;nbsp;a&amp;nbsp;transactional&amp;nbsp;context--&amp;gt; &lt;br /&gt;&amp;lt;!--If&amp;nbsp;you&amp;nbsp;change&amp;nbsp;this&amp;nbsp;bean's&amp;nbsp;id&amp;nbsp;to&amp;nbsp;any&amp;nbsp;string&amp;nbsp;other&amp;nbsp;than&amp;nbsp;"transactionManager",&amp;nbsp;you'll&amp;nbsp;have&amp;nbsp;to&amp;nbsp;specify&amp;nbsp;that&amp;nbsp;id&amp;nbsp;to&amp;nbsp;&amp;lt;tx:annotation-driven...&amp;gt;'s &lt;br /&gt;transaction-manager&amp;nbsp;attribute.&amp;nbsp;This&amp;nbsp;is&amp;nbsp;an&amp;nbsp;example&amp;nbsp;of&amp;nbsp;convention&amp;nbsp;over&amp;nbsp;configuration&amp;nbsp;which&amp;nbsp;makes&amp;nbsp;your&amp;nbsp;work&amp;nbsp;easier--&amp;gt; &lt;br /&gt;&amp;lt;bean&amp;nbsp;id="transactionManager"&amp;nbsp;class="org.springframework.orm.hibernate3.HibernateTransactionManager"&amp;gt; &lt;br /&gt;&amp;lt;property&amp;nbsp;name="sessionFactory"&amp;nbsp;ref="sessionFactory"/&amp;gt; &lt;br /&gt;&amp;lt;/bean&amp;gt; &lt;br /&gt;&lt;br /&gt;&amp;lt;!--repository&amp;nbsp;initialization--&amp;gt; &lt;br /&gt;&amp;lt;bean&amp;nbsp;id="repository.users"&amp;nbsp;class="com.springhibernate.integration.repository.HibernateUserBase" &lt;br /&gt;autowire="constructor"/&amp;gt; &lt;br /&gt;&amp;lt;/beans&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;5: Inside 'src/main/java/com/springhibernate/integration' create a package named 'repository'.&lt;br /&gt;6: Inside 'repository' package create an interface named 'UserBase' and it's implementation class named 'HibernateUserBase'&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration.repository;&lt;br /&gt;&lt;br /&gt;import com.springhibernate.integration.model.User;&lt;br /&gt;&lt;br /&gt;import java.util.List;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt;* @author Nabeel Ali Memon&lt;br /&gt;*/&lt;br /&gt;public interface UserBase {&lt;br /&gt;  public User getUser(Long id);&lt;br /&gt;  public List&lt;user&gt; getUsers();&lt;br /&gt;  public void addUser(User user);&lt;br /&gt;}&lt;br /&gt;&lt;/user&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration.repository;&lt;br /&gt;&lt;br /&gt;import com.springhibernate.integration.model.User;&lt;br /&gt;import org.hibernate.SessionFactory;&lt;br /&gt;import org.springframework.beans.factory.annotation.Autowired;&lt;br /&gt;import org.springframework.stereotype.Component;&lt;br /&gt;import org.springframework.stereotype.Repository;&lt;br /&gt;import org.springframework.transaction.annotation.Transactional;&lt;br /&gt;&lt;br /&gt;import java.util.List;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author Nabeel Ali Memon&lt;br /&gt; */&lt;br /&gt;&lt;br /&gt;@Repository&lt;br /&gt;@Transactional&lt;br /&gt;public class HibernateUserBase implements UserBase {&lt;br /&gt;  private SessionFactory sessionFactory;&lt;br /&gt;&lt;br /&gt;  @Autowired&lt;br /&gt;  public HibernateUserBase(SessionFactory sessionFactory) {&lt;br /&gt;    this.sessionFactory = sessionFactory;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  @Transactional&lt;br /&gt;  public User getUser(Long id) {&lt;br /&gt;    return (User) sessionFactory.getCurrentSession().get(User.class, id);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  @SuppressWarnings("unchecked")&lt;br /&gt;  @Transactional&lt;br /&gt;  public List&lt;user&gt; getUsers() {&lt;br /&gt;    return sessionFactory.getCurrentSession().createQuery("from User u").list();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  @Transactional&lt;br /&gt;  public void addUser(User user) {&lt;br /&gt;    sessionFactory.getCurrentSession().save(user);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/user&gt;&lt;/code&gt;&lt;/pre&gt;Notice @Repository annotation through which Spring container identifies this bean as a repository and @Transaction annotation which i've discussed in 'integration-data.xml'&lt;br /&gt;&lt;br /&gt;7: To test drive our configuration upto this point and have a taste of dependency injection using Spring 3 let's create a class 'App.java' under 'src/main/java/com/springhibernate/integration' having just a main method and try to print our user's email address to the console all the way from database and you'll see how Spring and Hibernate work in harmony.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration;&lt;br /&gt;&lt;br /&gt;import com.springhibernate.integration.model.User;&lt;br /&gt;import com.springhibernate.integration.repository.UserBase;&lt;br /&gt;import org.springframework.context.ApplicationContext;&lt;br /&gt;import org.springframework.context.support.ClassPathXmlApplicationContext;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt;* @author Nabeel Ali Memon&lt;br /&gt;*/&lt;br /&gt;public class App {&lt;br /&gt;  public static void main(String[] args) {&lt;br /&gt;    ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:META-INF/spring/*.xml");&lt;br /&gt;    UserBase users = (UserBase) ctx.getBean("repository.users");&lt;br /&gt;    User user = users.getUser(new Long(1));&lt;br /&gt;    System.out.println("User's email address: " + user.getEmail());&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Run it from your IDE or command line with the main class as 'App.java' and if all goes well, you should see this on your console:&lt;br /&gt;&amp;nbsp;"User's email address: nabeelalimemon@gmail.com"&lt;br /&gt;&lt;br /&gt;That marks the end of this part. I hope you learned and enjoyed. To get more explanation of what's going on just take a look at the comments i've written in .xml and .java files where necessary. Stay around for the next and probably last part of this tutorial series in which we'll turn this project into a web application.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5403612535047815315-2996775559006793907?l=nabeelalimemon.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nabeelalimemon.blogspot.com/feeds/2996775559006793907/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part_12.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/2996775559006793907'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/2996775559006793907'/><link rel='alternate' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part_12.html' title='Spring 3 integrated with Hibernate Part-B'/><author><name>Nabeel Ali Memon</name><uri>http://www.blogger.com/profile/02353619277056408053</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5403612535047815315.post-1460174956888440187</id><published>2010-05-12T00:57:00.009+05:00</published><updated>2010-06-14T10:44:14.962+05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Spring'/><category scheme='http://www.blogger.com/atom/ns#' term='Hibernate'/><title type='text'>Spring 3 integrated with Hibernate Part-A</title><content type='html'>Spring 3 has finally been released, a while back, with it's all new features offering a better developer experience. But there hasn't been any straight forward tutorial that could set you up on your path to roll out your application using dependency injection and web layer from Spring 3 and domain repositories through good old Hibernate. At least I couldn't find such a helpful stuff which i could use as a stub for my next project rapidly.&lt;br /&gt;&lt;br /&gt;There's already a tool(actually a great code-generator "Spring Roo") which brings up a Spring 3 based project within minutes but that doesn't tell you how features from Spring 3 actually work. To learn that, let's build our own project step by step.&lt;br /&gt;&lt;br /&gt;This tutorial will be broken into three parts. By the end of this series it'll have all the good stuff from Spring (that is Dependency Injection, MVC, Repository, Transaction demarcations, Aspects and all the fun) the Spring 3 way. We'll be using Hibernate for relational persistence mapping.&lt;br /&gt;&lt;br /&gt;In this Part(that is Part A) we will create a maven project first and make it talk to our database through Hibernate. So let's start some coding by creating a maven project.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;mvn&amp;nbsp;archetype:create&amp;nbsp;-DarchetypeArtifactId=maven-archetype-webapp&amp;nbsp;-DgroupId=com.springhibernate.integration&amp;nbsp;-DartifactId=spring-hibernate-webapp&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;Let's get into our newly created "spring-hibernate-webapp" directory and make this baby work with Intellij Idea by executing&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;mvn&amp;nbsp;idea:idea&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Of course you can use any IDE of your choice. Anyways, after you see a "BUILD SUCCESSFUL" message on the command line, open this project into Intellij Idea. To make this project use Spring 3, Hibernate, Log4j, some Apache libraries and a couple of maven plugins etcetera we need to configure our pom.xml (since pom.xml is fairly long, i've avoided writing it's content here. You can look at the source directly at&amp;nbsp;&lt;a href="http://code.google.com/p/spring3-hibernate-integration/source/browse/trunk/pom.xml"&gt;google-code hosting of this project&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;Let's configure Hibernate for this project and march towards the end of this part of series.&lt;br /&gt;&lt;br /&gt;1: Under 'src/main' you should have a source folder named 'java' (if not then create it).&lt;br /&gt;2: Under that folder create a package 'com.springhibernate.integration'.&lt;br /&gt;3: Create a class HibernateUtils.java under that package.&lt;br /&gt;4: At this point, to verify that all your maven dependencies are resolved and that your project setup is clean, you can create a main method inside inside HibernateUtils.java to print a greeting message like this&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration;&lt;br /&gt;&lt;br /&gt;import com.springhibernate.integration.model.User;&lt;br /&gt;import org.hibernate.Session;&lt;br /&gt;import org.hibernate.SessionFactory;&lt;br /&gt;import org.hibernate.cfg.Configuration;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt;* @author Nabeel Ali Memon&lt;br /&gt;*/&lt;br /&gt;public class HibernateUtils {&lt;br /&gt;  public static void main(String[] args) {&lt;br /&gt;    System.out.println("Working Correctly upto this point");&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;5: To execute it, go to command line and run these maven commands&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;mvn&amp;nbsp;compile&lt;br /&gt;mvn&amp;nbsp;-e&amp;nbsp;exec:java&amp;nbsp;-Dexec.mainClass="com.springhibernate.integration.HibernateUtils"&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;And you should successfully see&amp;nbsp;"Working Correctly upto this point".&lt;br /&gt;&lt;br /&gt;6: Now we need a relational database and a table to persist/retrieve our data. For all practical purposes, let's use MySQL by creating a database, a table and one entry to that table as following.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;create database test;&lt;br /&gt;use test;&lt;br /&gt;create table user (user_id int(11) primary key, first_name varchar(30), last_name varchar(30), email varchar(30));&lt;br /&gt;insert into user values(1, 'Nabeel', 'Memon', 'nabeelalimemon@gmail.com');&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;7: We'r done with the database part. Let's come back to our IDE and under the folder 'src/resources' create a new folder named 'mappings' and create a mapping file named 'user.hbm.xml' inside that folder. This mapping file should look like this:&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;?xml&amp;nbsp;version="1.0"?&amp;gt;&lt;br /&gt;&amp;lt;!DOCTYPE&amp;nbsp;hibernate-mapping&amp;nbsp;PUBLIC&lt;br /&gt;"-//Hibernate/Hibernate&amp;nbsp;Mapping&amp;nbsp;DTD&amp;nbsp;3.0//EN"&lt;br /&gt;"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;&amp;lt;class&amp;nbsp;name="com.springhibernate.integration.model.User"&amp;nbsp;table="USER"&amp;gt;&lt;br /&gt;&amp;lt;id&amp;nbsp;name="id"&amp;nbsp;column="USER_ID"&amp;gt;&lt;br /&gt;&amp;lt;generator&amp;nbsp;class="increment"/&amp;gt;&lt;br /&gt;&amp;lt;/id&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="firstName"&amp;nbsp;column="FIRST_NAME"/&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="lastName"&amp;nbsp;column="LAST_NAME"/&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="email"&amp;nbsp;column="EMAIL"/&amp;gt;&lt;br /&gt;&amp;lt;/class&amp;gt;&lt;br /&gt;&amp;lt;/hibernate-mapping&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;8: Under the package 'src/main/java/com/springhibernate/integration' create a package named 'model' and under that package create a class 'User.java' which is simply a Hibernate POJO for User entity.&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration.model;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author Nabeel Ali Memon&lt;br /&gt; */&lt;br /&gt;public class User {&lt;br /&gt;  private Long id;&lt;br /&gt;  private String firstName;&lt;br /&gt;  private String lastName;&lt;br /&gt;  private String email;&lt;br /&gt;&lt;br /&gt;  public User() { }&lt;br /&gt;&lt;br /&gt;  public Long getId() {&lt;br /&gt;    return id;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public void setId(Long id) {&lt;br /&gt;    this.id = id;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public String getFirstName() {&lt;br /&gt;    return firstName;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public void setFirstName(String firstName) {&lt;br /&gt;    this.firstName = firstName;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public String getLastName() {&lt;br /&gt;    return lastName;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public void setLastName(String lastName) {&lt;br /&gt;    this.lastName = lastName;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public String getEmail() {&lt;br /&gt;    return email;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public void setEmail(String email) {&lt;br /&gt;    this.email = email;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;9: Hey we haven't provided the hibernate configuration file yet, so let's create one under '/src/resources' named 'hibernate.cfg.xml'&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;&amp;lt;?xml&amp;nbsp;version='1.0'&amp;nbsp;encoding='utf-8'?&amp;gt;&lt;br /&gt;&amp;lt;!DOCTYPE&amp;nbsp;hibernate-configuration&amp;nbsp;PUBLIC&lt;br /&gt;"-//Hibernate/Hibernate&amp;nbsp;Configuration&amp;nbsp;DTD&amp;nbsp;3.0//EN"&lt;br /&gt;"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;hibernate-configuration&amp;gt;&lt;br /&gt;&amp;lt;session-factory&amp;gt;&lt;br /&gt;&amp;lt;!--&amp;nbsp;Database&amp;nbsp;connection&amp;nbsp;settings&amp;nbsp;--&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="connection.driver_class"&amp;gt;com.mysql.jdbc.Driver&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="connection.url"&amp;gt;jdbc:mysql://localhost:3306/test&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="connection.username"&amp;gt;username&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="connection.password"&amp;gt;password&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="format_sql"&amp;gt;true&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;!--&amp;nbsp;JDBC&amp;nbsp;connection&amp;nbsp;pool&amp;nbsp;(use&amp;nbsp;the&amp;nbsp;built-in)&amp;nbsp;--&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="connection.pool_size"&amp;gt;1&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;!--&amp;nbsp;SQL&amp;nbsp;dialect&amp;nbsp;--&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="dialect"&amp;gt;org.hibernate.dialect.MySQLDialect&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;!--&amp;nbsp;Enable&amp;nbsp;Hibernate's&amp;nbsp;automatic&amp;nbsp;session&amp;nbsp;context&amp;nbsp;management&amp;nbsp;--&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="current_session_context_class"&amp;gt;thread&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;!--&amp;nbsp;Disable&amp;nbsp;the&amp;nbsp;second-level&amp;nbsp;cache&amp;nbsp;&amp;nbsp;--&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="cache.provider_class"&amp;gt;org.hibernate.cache.NoCacheProvider&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;!--&amp;nbsp;Echo&amp;nbsp;all&amp;nbsp;executed&amp;nbsp;SQL&amp;nbsp;to&amp;nbsp;stdout&amp;nbsp;--&amp;gt;&lt;br /&gt;&amp;lt;property&amp;nbsp;name="show_sql"&amp;gt;true&amp;lt;/property&amp;gt;&lt;br /&gt;&amp;lt;!--&amp;nbsp;Drop&amp;nbsp;and&amp;nbsp;re-create&amp;nbsp;the&amp;nbsp;database&amp;nbsp;schema&amp;nbsp;on&amp;nbsp;startup&amp;nbsp;--&amp;gt;&lt;br /&gt;&amp;lt;!--property&amp;nbsp;name="hbm2ddl.auto"&amp;gt;update&amp;lt;/property--&amp;gt;&lt;br /&gt;&amp;lt;mapping&amp;nbsp;resource="mappings/user.hbm.xml"/&amp;gt;&lt;br /&gt;&amp;lt;/session-factory&amp;gt;&lt;br /&gt;&amp;lt;/hibernate-configuration&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;10: So now let's modify our 'HibernateUtil.java' exposing Hibernate Session Factory provider method(static) and get it to do some real stuff&lt;br /&gt;&lt;pre class="prettyprint"&gt;&lt;code&gt;package com.springhibernate.integration;&lt;br /&gt;&lt;br /&gt;import com.springhibernate.integration.model.User;&lt;br /&gt;import org.hibernate.Session;&lt;br /&gt;import org.hibernate.SessionFactory;&lt;br /&gt;import org.hibernate.cfg.Configuration;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author Nabeel Ali Memon&lt;br /&gt; */&lt;br /&gt;public class HibernateUtils {&lt;br /&gt;  private static final SessionFactory sessionFactory = buildSessionFactory();&lt;br /&gt;&lt;br /&gt;  private static SessionFactory buildSessionFactory() {&lt;br /&gt;    try {&lt;br /&gt;      // Create the SessionFactory from hibernate.cfg.xml&lt;br /&gt;      return new Configuration().configure().buildSessionFactory();&lt;br /&gt;    }&lt;br /&gt;    catch (Throwable ex) {&lt;br /&gt;      // Make sure you log the exception, as it might be swallowed&lt;br /&gt;      System.err.println("Initial SessionFactory creation failed." + ex);&lt;br /&gt;      throw new ExceptionInInitializerError(ex);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public static SessionFactory getSessionFactory() {&lt;br /&gt;    return sessionFactory;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public static void main(String[] args) {&lt;br /&gt;    Session session = getSessionFactory().getCurrentSession();&lt;br /&gt;    session.getTransaction().begin();&lt;br /&gt;    User user = (User) session.get(User.class, new Long(1));&lt;br /&gt;    System.out.println("user's email id is: "+user.getEmail());&lt;br /&gt;    session.getTransaction().commit();&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;Simply execute the HibernateUtil.java file from (your IDE or) command line using maven exec plugin like we did before and you should see our user's email address printed to screen.&lt;br /&gt;&lt;br /&gt;That marks our project's Hibernate usability. Hang on for the next part in which we actually configure Spring 3 in this project and introduce a Repository layer, Transactions and Logging Aspect being handled by Spring.&lt;br /&gt;&lt;br /&gt;Update 1:&amp;nbsp;&lt;a href="http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part_12.html"&gt;Spring 3 integrated with Hibernate Part-B&lt;/a&gt;&amp;nbsp;of this tutorial series is available now.&lt;br /&gt;&lt;br /&gt;Update 2: I've hosted the entire project at&amp;nbsp;&lt;a href="http://code.google.com/p/spring3-hibernate-integration/"&gt;code.google.com&lt;/a&gt;&amp;nbsp;and have open sourced it under Apache 2 license. Enjoy!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5403612535047815315-1460174956888440187?l=nabeelalimemon.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://nabeelalimemon.blogspot.com/feeds/1460174956888440187/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/1460174956888440187'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5403612535047815315/posts/default/1460174956888440187'/><link rel='alternate' type='text/html' href='http://nabeelalimemon.blogspot.com/2010/05/spring-3-integrated-with-hibernate-part.html' title='Spring 3 integrated with Hibernate Part-A'/><author><name>Nabeel Ali Memon</name><uri>http://www.blogger.com/profile/02353619277056408053</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
