Saturday, January 28, 2012

Spring MVC 3.1, jqGrid, and Spring Data JPA Integration Guide (Part 5)

Review

We have just completed our application! In the previous sections, we have discussed the functional specs, created the Java classes, declared the configuration files, and wrote the HTML files. In this section, we will build and run the application using Maven, and show how to import the project in Eclipse.


Running the Application

Access the source code

To download the source code, please visit the project's Github repository (click here)

Preparing the data source

  1. Run MySQL (install one if you don't have one yet)
  2. Create a new database:
    spring_jqgrid_tutorial
  3. Import the following file which is included in the source code under the src/main/resources folder:
    spring_jqgrid_tutorial.sql

Building with Maven

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn tomcat:run
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'tomcat'.
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from central
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from snapshots
    [INFO] ------------------------------------------
    [INFO] Building spring-jqgrid-tutorial Maven Webapp
    [INFO]    task-segment: [tomcat:run]
    [INFO] ------------------------------------------
    [INFO] Preparing tomcat:run
    [INFO] [apt:process {execution: default}]
    [INFO] [resources:resources {execution: default-resources}]
    [INFO] [tomcat:run {execution: default-cli}]
    [INFO] Running war on http://localhost:8080/spring-jqgrid-tutorial
    Jan 28, 2012 11:15:25 AM org.apache.catalina.startup.Embedded start
    INFO: Starting tomcat server
    Jan 28, 2012 11:15:25 AM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
    Jan 28, 2012 11:15:26 AM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    Jan 28, 2012 11:15:32 AM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Jan 28, 2012 11:15:32 AM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    
  5. Note: If the project will not build due to missing repositories, please enable the repositories section in the pom.xml!

Access the Entry page

  1. Follow the steps with Building with Maven
  2. Open a browser
  3. Enter the following URL (8080 is the default port for Tomcat):
    http://localhost:8080/spring-jqgrid-tutorial/

Import the project in Eclipse

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn eclipse:eclipse -Dwtpversion=2.0
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'eclipse'.
    [INFO] org.apache.maven.plugins: checking for updates from central
    [INFO] org.apache.maven.plugins: checking for updates from snapshots
    [INFO] org.codehaus.mojo: checking for updates from central
    [INFO] org.codehaus.mojo: checking for updates from snapshots
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from central
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from snapshots
    [INFO] -----------------------------------------
    [INFO] Building spring-jqgrid-tutorial Maven Webapp
    [INFO]    task-segment: [eclipse:eclipse]
    [INFO] -----------------------------------------
    [INFO] Preparing eclipse:eclipse
    [INFO] No goals needed for project - skipping
    [INFO] [eclipse:eclipse {execution: default-cli}]
    [INFO] Adding support for WTP version 2.0.
    [INFO] -----------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] -----------------------------------------
    
    This command will add the following files to your project:
    .classpath
    .project
    .settings
    target
    You may have to enable "show hidden files" in your file explorer to view them
  5. Open Eclipse and import the project

Conclusion

That's it! We've have successfully completed our Spring MVC 3.1 web application. We've learned how to integrate with jqGrid and add AJAX functionality to make the application responsive.

I hope you've enjoyed this tutorial. Don't forget to check my other tutorials at the Tutorials section.

Revision History


Revision Date Description
1 Jan 28 2012 Uploaded tutorial and Github repository
2 Jan 30 2012 Update Functional Specs
3 Feb 11 2012 Update to Spring Data JPA 1.1.0 RC1

StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1, jqGrid, and Spring Data JPA Integration Guide (Part 5) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

40 comments:

  1. I really enjoyed this tutorial. Always a pleasure reading your blog. Thank you very much by the knowledge that you share in a simple way.

    Sorry for my english. I'm from Argentina and I don't speak english very well.

    ReplyDelete
  2. Hi i have downloaded the code and it is working perfectly fine. i am clicking on the column name to see the sorting but looks like it is not happening. Any idea?

    ReplyDelete
  3. @Anonymous, I haven't implemented the sorting feature yet. To apply sorting, you have to basically use the sord (sort order) and sidx (the column to sort). That example is shown in the jsonquery library.

    ReplyDelete
  4. Hi Krams,

    Thanks for your reply. i am trying to see how to get the criteria api working for the database columns using jpa specifications. Do you have any example on that. i wanted to build a query based on the inputs from the search filter of the JQuery JqGRID GUI

    ReplyDelete
  5. Hi Krams,
    Many Thanks for your great works. Fantastic tutorials. I learned quite a lot. All worked for me except JPA query.
    I write query like this

    @Query("select u from user u where u.username like :username order by :sidx ")
    Page findByUsernameLikeT(@Param("username") String username,@Param("sidx") String sidx, Pageable pageable);

    And passed the sidx value 'username desc'.
    So the query would be 'select u from user u where u.username like '%j%' order by username desc.
    This always return ascending order, not descending order.

    Any suggestion please.

    Thanks in advance
    Rajesh

    ReplyDelete
  6. Hi Krams,

    I was able to add sorting by using the overloaded constructor passing in the Sort object:

    Pageable pageRequest = new PageRequest(page - 1, rows, new Sort((sord.equals("asc") ? Direction.ASC : Direction.DESC), sidx));

    However this does not work when sorting the "Role". Any ideas why?

    Thanks and more power to you!
    Allan

    ReplyDelete
    Replies
    1. Krams, Allan,

      I found a solution to sort based on foreign key relationships. The solution is to replace the sidx with the foreign table name and field name as follows:

      sidx = roleId.username

      and then I implemented my own custom findAll function in the repository that inner joins the 2 tables that returns the records plus the foreign username field.

      Thanks,

      Alberto

      Delete
    2. I am very new to jQuery and this is the first application which ran in first go. I will appriciate if some one provide how to sort on role column. I am new to JPA queries as well.

      Delete
    3. For FK relationship sorting you need to use domain object properties. Here solution is to replace the field name as :

      sidx = "role.role";

      We are considering role because User domain object contain role field whose id is actually stored in Role domain class in field "role".

      Now set this value in pageRequest object and add method which will join with role table
      ex:

      @Query("select u from user u inner join u.role r")
      function.......

      Hence after applying sorting on role column hibernate query generated will be -

      select user0_.*
      from user user0_
      cross join role role1_
      where user0_.id=role1_.user_id
      order by role1_.role asc limit ?

      Delete
  7. @Anonymous, I'm not sure if you can sort based on foreign key relationships when using the Spring Data Repository. You will have to use @Query and specify a custom JPQL for that. But if you're willing, you can explore the jsonquery library I've created (see my notes in this tutorial). That allows you full sorting without doing extra work and manually writing JPQL or SQL

    ReplyDelete
  8. Hi Krams,
    I took your latest code and trying to deploy on tomcat 7 but found the following error during deployment.
    Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/data/jpa]
    Offending resource: ServletContext resource [/WEB-INF/spring-data.xml]

    Would you please check?

    Thanks and Regard
    John

    ReplyDelete
    Replies
    1. I had the same problem. The solution is to change namespace in xsi:schemaLocation
      from:
      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
      to:
      http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd

      BR
      Roman

      Delete
  9. It appears the pluginRepository http://evgeny-goldin.org/artifactory/repo/ doesn't exist anymore. I think for that reason I get the following error.

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring-data.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name 'hibernatePersistenceUnit' found

    What's the workaround?

    ReplyDelete
  10. Hi krams,

    Nice tutorial. I learned a lot. But i am getting the error shown below.

    java.lang.IllegalArgumentException: No persistence unit with name 'hibernate PersistenceUnit' found.
    And u mentioned META-INF/persistence.xml. i didn't find that file in the META-INF.

    Regards
    Suhashini Dharmisetty

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Great tutorials. I am running into an exception that I cannot figure out. I downloaded the code, (the zip code package), extracted it, created the database and ran the script, and ran the code mvn tomcat:run

    I have been able to run at least 5 or 6 other tutorials but this one is giving me issues. Anyone ideas?

    [ERROR] [main 11:48:41] (ContextLoader.java:initWebApplicationContext:307) Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies
    failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.krams.repository
    .UserRepository org.krams.controller.UserController.repository; nested exception is org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NoSuchMethodE
    rror: org.springframework.data.repository.core.RepositoryMetadata.getDomainClass()Ljava/lang/Class;

    @Podilidasu
    For the persistence.xml issue, my workaround was to copy the file to the WEB-INF and change the path to it. This was for the spring-hibernate-jpa-many-to-one-default.

    persistenceXmlLocation=classpath*:persistence.xml

    ReplyDelete
  13. ahh..fixed the issue. Long story short, just use the latest version of the spring-data-jpa. I thought I had tried this, but I was updating the pom and building on a different copy of the project.

    1.1.0.RELEASE

    ReplyDelete
    Replies
    1. This worked for me in first go. Thanks for info.

      Delete
    2. Hello everybody, I had the same problem and solve it add this to my pom.xml,

      org.springframework.data
      spring-data-jpa
      1.1.0.BUILD-SNAPSHOT

      Thanks Walter, y kramms

      Delete
  14. Hi when I am trying to build the project by giving mvn tomcat:run command I am getting following error and build is getting failed.
    1 required artifact is missing.

    for artifact:
    org.krams:spring-jqgrid-tutorial:war:0.0.1-SNAPSHOT

    HOW CAN I RESOLVE THIS??

    ReplyDelete
  15. The current "spring.data.jpa.version" in pom.xml
    "1.1.0.RC1"

    When you change this Code to;
    "1.1.0.RELEASE"

    It works fine:)
    ALSO THANKS KRAMS

    ReplyDelete
  16. I've gone through the tutorial and all compiles fine. However, using tomcat 7 and building in intellij I can't seem to get the src/main/web-app/resource directories to copy over to the build target ... Keep coming up with 404's ...

    ReplyDelete
  17. I edited this tutorial to support an Annotated Config like your thymeleaf tutorial and it works great ... :-) I did have to change the @NamedQuery though ... I was getting 500 errors when trying to update or edit a user ...

    @NamedQuery( query = "select u from user u where u.username = ?1", name = User.FIND_BY_USERNAME )

    ReplyDelete
    Replies
    1. That's great to know. I have plans to update my older tutorials to JavaConfig (and still keeping XML-based config) but I just don't have enough time to do those :-)

      Delete
  18. This is a good example, thank you but , why all google results are the same? I would like to find another example. i´m not sure but it could be bad for your blog... Please stop referencing your blog everywhere.

    ReplyDelete
    Replies
    1. I don't know what you mean by referencing my blog anywhere. My blog only exist here. It's possible some readers are making links or sharing tweets about my blog. I actually discovered that one time (to my surprise). It's good I think because the articles are discoverable.

      I won't be surprised if you won't find any articles relating with jqGrid and Spring because I think there's quite few people who write about these. I think I'm the only one when I started this article. Maybe there's now two or three (but I doubt it).

      Delete
  19. This gives me an exception I am attaching the stack trace below. kindly help me . I am new to Spring.

    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring-data.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name 'hibernatePersistenceUnit' found

    ReplyDelete
  20. Thanks for your tutorial.Its very helpful to me. when i start the tomcat server then it sows the following exception.Please can any one help me........


    [ERROR] [localhost-startStop-1 12:17:25] (ContextLoader.java:initWebApplicationContext:312) Context initialization failed
    java.lang.NoClassDefFoundError: org/springframework/beans/factory/NoUniqueBeanDefinitionException
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
    at java.lang.Class.getDeclaredMethods(Class.java:1855)
    at org.springframework.core.type.StandardAnnotationMetadata.hasAnnotatedMethods(StandardAnnotationMetadata.java:136)
    at org.springframework.context.annotation.ConfigurationClassUtils.isLiteConfigurationCandidate(ConfigurationClassUtils.java:105)
    at org.springframework.context.annotation.ConfigurationClassUtils.checkConfigurationClassCandidate(ConfigurationClassUtils.java:86)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:216)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:178)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:617)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
    Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.NoUniqueBeanDefinitionException
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
    ... 22 more

    ReplyDelete
    Replies
    1. I solve my problem.......just replease spring.data.jpa.version->1.1.0.RELEASE to
      1.1.0.M1 and add dependency spring-beans.Its work very nice.Again thanks
      Mark Serrano aka krams for a helpful tutorial.It helps me lot..........

      Delete
  21. Hi, I am having this error while running the code in eclipse.

    Plugin execution not covered by lifecycle configuration: com.mysema.maven:maven-apt-plugin:1.0:process (execution: default, phase: generate-sources)

    Could you please help me out in this.

    ReplyDelete
  22. I am new to SpringMVC and jqgrid. Anyway, great tutorial. I have this error in the POM file "Plugin execution not covered by lifecycle configuration: com.mysema.maven:maven-apt-plugin:1.0:process (execution: default, phase: generate-sources)". Please help? Thank you.

    ReplyDelete
  23. I have read your blog its very attractive and impressive. I like it your blog.

    Spring online training Spring online training Spring Hibernate online training Spring Hibernate online training Java online training

    spring training in chennai spring hibernate training in chennai

    ReplyDelete
  24. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done an outstanding job.

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  25. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    core java training in Electronic City

    Hibernate Training in electronic city

    spring training in electronic city

    java j2ee training in electronic city

    ReplyDelete
  26. I recently came across your blog and have been reading along. I thought I would leave my first comment.
    python training in tambaram | python training in annanagar | python training in jayanagar

    ReplyDelete
  27. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in velachery| rpa training in tambaram |rpa training in sholinganallur | rpa training in annanagar| rpa training in kalyannagar

    ReplyDelete
  28. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    Java training in Chennai | Java training in Bangalore

    Java interview questions and answers | Core Java interview questions and answers

    ReplyDelete