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:
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.
First, create new Maven project on STS. Skip archetype selection. Pick maven group id, artifact id and select packaging to war.
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…).
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 */
}
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;
}
}
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";
}
}
Add a JSP view to list all the pizza entities passed by the controller src/main/webapp/WEB-INF/index.jsp
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
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:
Click Run and navigate your browser to http://localhost:8080/pizzashop
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:
32 thoughts on “Spring MVC + Hibernate + MySQL Quick Start From Scratch”
Excellent Article.
Reply
I got a 404 error when try to run with eclipse and jboss..
Reply
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.
you sir just made my day, this setup has been killing me for days, thanks.
Reply
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 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.
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
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
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)
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
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?
That’s a great tutorial! Would be interesting to see the same sort of quick start for the Spring MVC / jOOQ / MySQL stack!
Reply
great tutorial for a beginner like me thanks a lot
Reply
great tutorial . thanks Garry . may I copy/paste/print your tutorials , and use your code ?
Reply
Ofcourse, just provide a link back to my blog post. Thanks
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
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
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.
No Spring WebApplicationInitializer types detected on classpath
i am getting this error when i run the application.
Reply
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
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
Are you sure your context root is /Pizzashop with uppercase P?
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
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)
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
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
which jar files need to download & where I should add them, I am getting confused
Reply
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
nicely explained. Thanks for sharing the info.
Reply
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
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
Excellent Article.
I got a 404 error when try to run with eclipse and jboss..
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.
you sir just made my day, this setup has been killing me for days, thanks.
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:
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.
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!
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
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)
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
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?
Yes I’ve written another post related to entity relationship, please see here: https://gerrydevstory.com/2013/07/02/hibernate-one-to-many-relationship/
That’s a great tutorial! Would be interesting to see the same sort of quick start for the Spring MVC / jOOQ / MySQL stack!
great tutorial for a beginner like me thanks a lot
great tutorial . thanks Garry . may I copy/paste/print your tutorials , and use your code ?
Ofcourse, just provide a link back to my blog post. Thanks
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
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?
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.
No Spring WebApplicationInitializer types detected on classpath
i am getting this error when i run the application.
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
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
Are you sure your context root is /Pizzashop with uppercase P?
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)
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)
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
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 intowhich jar files need to download & where I should add them, I am getting confused
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
nicely explained. Thanks for sharing the info.
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
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