Spring MVC + Hibernate + MySQL Quick Start From Scratch

This is a tutorial to build a very simple pizzashop Spring MVC, Hibernate and MySQL application. The main page shows all pizza rows stored on a database table:

03

Technology in Java world moves very fast. Using straight Hibernate might no longer be preferable since Java EE 5 introduces JPA (Java Persistence API) but it’s still good to learn anyway. Spring MVC and Hibernate is one of the most popular Java libraries used out there.

Tools / Environment Required
If you’re just starting fresh and don’t have most of the tools below just install JDK, STS (Springsource Tools Suite) and MySQL server, everything else is bundled within them.

Project Setup and Boilerplate

  1. First, create new Maven project on STS. Skip archetype selection. Pick maven group id, artifact id and select packaging to war.01 02

  2. By default Maven will use JDK 1.5, re-configure it to use 1.6. Add following maven-compiler-plugin section to pom.xml under element. Ensure the change takes effect by updating maven project settings (right click on project -> Maven -> Update project…).
    
      
        
          org.apache.maven.plugins
          maven-compiler-plugin
          3.1
          
            1.6
            1.6
          
        
      
    
    

  3. Add Spring, Hibernate, Java EE and MySQL maven dependencies to pom.xml. Place following under element.
    
      3.2.3.RELEASE
      4.2.2.Final
    
    
    
      
      
        org.springframework
        spring-context
        ${spring.version}
      
      
        org.springframework
        spring-webmvc
        ${spring.version}
      
      
        org.springframework
        spring-orm
        ${spring.version}
      
      
      
      
        org.hibernate
        hibernate-core
        ${hibernate.version}
      
      
      
      
        javax.servlet
        servlet-api
        2.5
        provided
      
      
        jstl
        jstl
        1.2
      
      
      
      
        commons-dbcp
        commons-dbcp
        1.4
      
      
        mysql
        mysql-connector-java
        5.1.25
      
      
    
    

  4. Create a web.xml descriptor file with Spring MVC servlet setup on it, place it on src/main/webapp/WEB-INF
    
    
    
      
        appServlet
        org.springframework.web.servlet.DispatcherServlet
        
          contextConfigLocation
          /WEB-INF/servlet-context.xml
        
        1
      
       
      
        appServlet
        /
      
      
    
    

  5. Create src/main/webapp/WEB-INF/servlet-context.xml Spring bean config file for dispatcher servlet. We configure few important stuffs in here:
    
    
    
      
      
    
      
      
        
        
      
      
      
      
      
      
      
        
        
        
        
        
      
      
      
      
        
        
          
            com.gerrytan.pizzashop
          
        
        
          
            hibernate.dialect=org.hibernate.dialect.MySQLDialect
          
        
      
      
      
      
        
      
      
      
      
    
    
    


The Business Functionality

  1. Now all the boilerplate code done, we can start coding the business functionality. For this simple app we will have a pizza database table with just id, name and price column. Create the Pizza entity class representing the table
    package com.gerrytan.pizzashop;
    // imports ..
    
    
    (name = "pizza")
    public class Pizza {
      @Id  private long id;
      private String name;
      private double price;
      /* getters & setters */
    }
    

  2. Create a DAO class to obtain Pizza entity persisted on database. Note that we won’t create service layer classes for the sake of simplicity (on real-life complex business application adding service layer is a good practice).
    package com.gerrytan.pizzashop;
    // imports..
    
    
    s({"unchecked", "rawtypes"})
    public class PizzaDAO {
       private SessionFactory sessionFactory;
      
      /**
       *  annotation below will trigger Spring Hibernate transaction manager to automatically create
       * a hibernate session. See src/main/webapp/WEB-INF/servlet-context.xml
       */
      
      public List findAll() {
        Session session = sessionFactory.getCurrentSession();
        List pizzas = session.createQuery("from Pizza").list();
        return pizzas;
      }
    }
    

  3. Create a Spring MVC controller to handle request from the main page. Note that PizzaDAO reference is injected, and after collection of Pizza entity objects are obtained it’s passed to the view using Model object.
    package com.gerrytan.pizzashop;
    // imports..
    
    
    ("/")
    public class PizzaController {
      
       private PizzaDAO pizzaDAO;
      
      /**
       * This handler method is invoked when
       * http://localhost:8080/pizzashop is requested.
       * The method returns view name "index"
       * which will be resolved into /WEB-INF/index.jsp.
       *  See src/main/webapp/WEB-INF/servlet-context.xml
       */
      (method = RequestMethod.GET)
      public String list(Model model) {
        List pizzas = pizzaDAO.findAll();
        model.addAttribute("pizzas", pizzas);
        return "index";
      }
    }
    

  4. Add a JSP view to list all the pizza entities passed by the controller
    src/main/webapp/WEB-INF/index.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    
    
    
    Pizzashop
    
    
            

    List of All Pizzas

    • ${p.id} - ${p.name} - ${p.price}

  5. And finally prepare MySQL pizzashop database schema:
    CREATE SCHEMA `pizzashop`;

    And pizza table:

    CREATE  TABLE `pizzashop`.`pizza` (
      `id` BIGINT NOT NULL AUTO_INCREMENT ,
      `name` VARCHAR(45) NULL ,
      `price` DOUBLE NULL ,
      PRIMARY KEY (`id`) );
    

    And insert some data into it

    INSERT INTO `pizzashop`.`pizza` (`id`, `name`, `price`) VALUES ('I', 'Italian', '7.5');
    INSERT INTO `pizzashop`.`pizza` (`id`, `name`, `price`) VALUES ('2', 'Thin Crust', '6');
    INSERT INTO `pizzashop`.`pizza` (`id`, `name`, `price`) VALUES ('3', 'Pepperoni', '6.2');
    

    It is assumed you have MySQL server running on your local machine (localhost) on the default port 3306. The name of the schema is pizzashop and table pizza. Have a look at Spring beans configuration section above to reconfigure this.

Running The Code

  1. The easiest way to run your code is using in-memory Maven Tomcat plugin. It will launch on-the-fly Tomcat server with your code deployed. Make sure your project is selected on the project exploded and setup a maven run configuration on STS. Go to Run -> Run Configurations.. and create a new maven build entry like this:
    maven goal
  2. Click Run and navigate your browser to http://localhost:8080/pizzashop

Download The Source Code

Source code for this demonstration can be obtained using git:

git clone https://bitbucket.org/gerrytan/pizzashop.git -b basic

Congratz!

Well done on making it this far. Hopefully that was a quick and nice introduction to Spring MVC + Hibernate + MySQL and you can see how the tedious database to java class mapping is now simplified. You might have lots of questions in your mind by now — feel free to ask in the comment section below. Following are few official references and community article links you can browse around:

See Also

32 thoughts on “Spring MVC + Hibernate + MySQL Quick Start From Scratch”

    1. First check what context path deployed on JBoss. If your app filename is pizzashop-1.0.war then it will be . Your JBoss logs should tell you more.

      However I wouldn’t recommend JBoss if you’re a beginner because JBoss came with its own Hibernate at runtime which often causes conflicts. See my post about running Spring with JBoss.

  1. good tutorial bro, but why i got and error after improve your code with service layer. before i added service layer your code worked perfectly

    org.springframework.beans.factory.BeanCreationException:

    Reply
    1. org.springframework.beans.factory.BeanCreationException can be caused by many things. You need to look further up what’s causing this. Common causes are failed autowiring, null pointer reference, etc.

  2. Hi, I’m having a little problem getting the app to run. Can you please offer any insights?

    The error I keep getting is…

    No plugin found for prefix ‘org.apache.tomcat.maven.tomcat7-maven-plugin’ in the current project and in the plugin groups …

    I still get the error after adding the plugin to the pom.xml build plugins element like this:

    org.apache.tomcat.maven
    tomcat7-maven-plugin
    2.2

    Thanks!

    Reply
    1. This is most likely because your maven is setup not to look for unknown plugin directly from central, eg: you have an internal company maven repository proxy. Have a look at your ~/.m2/repository and check if your maven is using any mirror, and ensure tomcat7 plugin is available on the mirror / use another mirror. Stack overflow has a lost of question posted about this problem

    2. I know it’s been ages since this but your main problem is you wrote it wrong, it’s:
      org.apache.tomcat.maven:tomcat7-maven-plugin (: instead of . after maven)

    3. No mapping found for HTTP request with URI [/pizzashop/] in DispatcherServlet with name ‘appServlet’

      now im getting this error in my console please solve me
      thanq

  3. I got this to work, however, after looking at the source code provided I noticed a ‘Topping’ class/table that is not talked about in this tutorial and I’d like to add that to my ‘pizzashop’ project.

    Is there a followup to this tutorial that adds additional functionality?

    Reply
  4. great tutorial . thanks Garry . may I copy/paste/print your tutorials , and use your code ?

    Reply
  5. thanks . gary mak wrote book spring recipes . simply explaining great things . you have same feature of teaching and it will be great if we get book from you . there is still hard need of good spring books in the world I think

    Reply
  6. I tried this code in my java application. I got a null pointer exception at the controller class on the following line.

    List users = sampleDao.findAll();
    Please could you tell me whats wrong?

    Reply
    1. Probably you haven’t autowired the SampleDAO class or the annotation scanning didn’t work. It’s hard to trace without seeing your code. If you keep getting error I recommend uploading your project to github and share the link for others to test.

  7. No Spring WebApplicationInitializer types detected on classpath

    i am getting this error when i run the application.

    Reply
    1. That doesn’t seem like an error to me. WebApplicationInitializer is used for servlet 3, while this tutorial still uses servlet 2.5 web.xml. I think your error is somewhere else

  8. Hi gerrytan, I am getting `WARNING: No mapping found for HTTP request with URI [/Pizzashop/] in DispatcherServlet with name ‘appServlet’`
    when running the project in eclipse via “Run As -> on tomcat7 server” and of course brings me 404 error.
    If I change / to /Pizzashop the WARNING disappears but is still unavailable :(

    Reply
  9. Hi Gerrytan. I’m using IntelliJ IDEA 13 and I have such error :
    HTTP Status 500 – Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

    Seems like its problem in this query in code:

    private SessionFactory mySessionFactory; // could not autowire. No beans in ‘SessionFactory’ type found.

    List pizzas = session.createQuery(“from Pizza”).list(); // Pizza is underlined

    List pizzas = session.createQuery(“select distinct p from Pizza as p left join fetch p.toppings”).list(); //// Pizza is underlined

    Please tell me what i have to do to solve it.
    Thank you)

    Reply
    1. IntelliJ is only IDE, wouldn’t affect your application. Your problem is to do with session factory setup. In my example I setup local session factory on servlet-context.xml (LocalSessionFactoryBean). Check further up in the stack trace what causes this to fail (invalid database host/port/user/pass is a common problem)

  10. Thanks and I got an error like below

    HTTP Status 404 -

    type Status report

    message

    description The requested resource () is not available.
    Apache Tomcat/7.0.10

    Reply
    1. It’s either your binding your context root to the wrong path or your server did not start up correctly. Were there any error when tomcat starts? What is your artifactId on pom.xml, this will be your context root. Eg: if you have helloworld, the embedded tomcat container will deploy it into

  11. which jar files need to download & where I should add them, I am getting confused

    Reply
    1. I used maven, a popular dependency management (jar) tool for Java. By declaring the dependencies on pom.xml maven will automatically determine if you have it in your PC, or figure out where to download it from the internet. Read more: http://maven.apache.org

  12. Hi.
    I’m newbie.

    Everything works great in console, but I cannot access localhost:8080/pizzashop in web browser. Usually I user: run as / run on server to launch web browser. Using maven build, I cannot see how to do it.

    STS 3.5.1
    jdk1.8

    Thanks

    Reply
    1. I prefer using embedded tomcat container on Maven to avoid having to setup server in eclipse, hence you don’t have to do run as / run on server

Leave a Reply