Tag Archives: sql

Creating a Minimal Spring MVC, JPA / Hibernate and MySQL Project

The goal of this article is to create a bare minimum Spring MVC project with JPA (with Hibernate provider) as persistence provider and MySQL as the DBMS. To test everything works I’ll also add a form page allowing you to list all entities and add a new one.

Environment:

  • jdk 6
  • Spring 3.2.8.RELEASE
  • Hibernate 4.3.3.Final
  • STS 3.4.0.RELEASE
  • MySQL database running on localhost port 3306. The database name is hello with username root and no password.

Steps:

  1. From STS, create a new Maven Project. Since we’re starting from scratch, tick Create a simple project (skip archetype selection). Hit Next.
    jpaminimal0
  2. On the next New Maven Project dialog that comes up, give it a group id, artifact id and set the packaging to war. A minimal maven project will be setup for you when you hit Finish
  3. The default maven project is setup to use jdk 1.5, to switch it to 1.6, open pom.xml and add following xml section under the element.
    
      
        
          maven-compiler-plugin
          
            1.6
            1.6
          
        
      
    
    

    Right click the project on Package Explorer -> Maven -> Update Project.. once this is done to update the eclipse build path into jdk 1.6

  4. Add maven dependencies for Spring, JPA, Hibernate, Java EE, MySQL and other supporting jars. Again this goes to your pom.xml

    
      
      
        org.springframework
        spring-context
        3.2.8.RELEASE
      
    
      
        org.springframework
        spring-webmvc
        3.2.8.RELEASE
      
    
      
        org.springframework
        spring-orm
        3.2.8.RELEASE
      
    
      
      
        org.hibernate
        hibernate-core
        4.3.3.Final
      
    
      
        org.hibernate
        hibernate-entitymanager
        4.3.3.Final
      
    
      
      
        javax.servlet
        servlet-api
        2.5
        provided
      
    
      
        javax.servlet.jsp
        jsp-api
        2.1
        provided
      
    
      
        javax.servlet
        jstl
        1.2
      
    
      
      
        mysql
        mysql-connector-java
        5.1.29
      
    
      
        commons-dbcp
        commons-dbcp
        1.4
      
    
      
        xerces
        xercesImpl
        2.11.0
      
    
    
  5. Create the web deployment descriptor src/main/webapp/WEB-INF/web.xml. We will setup Spring MVC here with bean context configuration xml file set to /WEB-INF/spring-context.xml
    
    
      
      
        appServlet
        org.springframework.web.servlet.DispatcherServlet
        
          contextConfigLocation
          /WEB-INF/spring-context.xml
        
        1
      
      
      
        appServlet
        /
      
    
    
  6. Create a Spring Bean Configuration File placed on src/main/webapp/spring-context.xml. There are plenty important setups here including annotation-based MVC controller, view resolver, transaction config, data source, entityManagerFactory and transaction manager.
    
    
    
      
      
      
      
      
      
      
      
        
        
      
      
      
      
        
        
        
        
      
      
      
      
        
        
      
      
      
      
        
      
      
      
      
    
    
    
  7. Create src/main/resources/META-INF/persistence.xml. This is the persistence unit configuration. It tells JPA what provider will be used, persistence unit type and hibernate configs.
    
    
    
      org.hibernate.ejb.HibernatePersistence
        
            
            
            
            
        
      
    
    
  8. Create a simple entity class to test our setup. Let’s call this entity Person. It has an id and name field.

    package hello;
    
    
    (name = "person")
    public class Person {
    
      @Id
      
      private int id;
    
      private String name;
      
      /* getters & setters */
    
    }
    
  9. And setup mysql database and table to store this entity. The table columns correspond to the Person class fields above. Also note we inform JPA of mysql AUTO_INCREMENT by using annotation:

    CREATE DATABASE IF NOT EXISTS hello;
    
    USE hello;
    
    CREATE TABLE person (
      id INT PRIMARY KEY AUTO_INCREMENT,
      name VARCHAR(50)
    );
    
  10. Create a simple service to list all and add a Person entity

    package hello;
    
    
    public class PersonService {
      
      // An EntityManager will be automatically injected from EntityManagerFactory setup on
      // spring-context.xml
      ext
      private EntityManager em;
      
      // Since we've setup  and transaction manager on spring-context.xml,
      // any bean method annotated with  will cause Spring to magically call
      // begin() and commit() at the start/end of the method. If exception occurs it will also
      // call rollback()
      
      public List getAll() {
        List result = em.createQuery("SELECT p FROM Person p", Person.class).getResultList();
        return result;
      }
      
      
      public void add(Person p) {
        em.persist(p);
      }
    }
    
  11. Create a HomeController class to map HTTP requests. The package name I used is hello:
    package hello;
    
    
    ("/")
    public class HomeController {
    
       private PersonService personSvc;
      
      /**
       * Requests to http://localhost:8080/hello will be mapped here.
       * Everytime invoked, we pass list of all persons to view
       */
      (method = RequestMethod.GET)
      public String listAll(Model model) {
        model.addAttribute("persons", personSvc.getAll());
        return "home";
      }
      
      /**
       * POST requests to http://localhost:8080/hello/addPerson goes here.
       * The new person data is passed from HTML from and bound into the
       * Person object.
       */
      (value = "/addPerson", method = RequestMethod.POST)
      public String addPerson( Person person) {
        personSvc.add(person);
        return "redirect:/";
      }
    }
    
  12. Finally add the form jsp file located on src/main/webapp/WEB-INF/home.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" %>
    
    
    
    
    Hello
    
    
      

    All Persons

    Id: ${p.id} Name: ${p.name}

    Add New

    Name:

    This is a simple form which will list all persons and allow you to add one

    Screen Shot 2014-03-03 at 9.51.39 pm

Check Out The Source

You can browse / clone the source code of this article on github. To run this on STS:

  1. Clone it using git
    git clone :gerrytan/jpaminimal.git
  2. On STS, do File > Import > Existing Maven Projects
  3. Create run configuration (Run > Run Configurations…) like this
    mvn-run-config
  4. Make sure the project is selected on the project explorer and run it. This will fire up in-memory tomcat7 server at http://localhost:8080

Backing Up and Restoring MySQL Database Using mysqldump

Although not always the most efficient, mysqldump is a handy way to migrate your MySQL server — particularly if you don’t have many schemas and the size of data is small.

To create backup, first list all schemas on the server using

SHOW DATABASES;

I normally avoid backing up performance_schema, information_schema and mysql schema. They contain database configuration, user settings etc. This would mean you have to reconfigure all your settings on the new server

Then take the dump of all schema using this command:

mysqldump -u***** -p***** --databases  > mybackup_20131107_1223.sql

Then compress, transfer and inflate the sql file into the new server’s host. When you’re ready to restore, just do

mysql -u***** -p***** < mybackup_20131107_1223.sql