Spring MVC Hibernate Mysql integration CRUD Example Tutorial

Spring MVC Hibernate Mysql integration CRUD example tutorial show you how to integrate Spring with Hibernate and Mysql using annotation based configuration. We will create a simple CRUD web application that permits us input user data on form and save that data in MySQL database using Hibernate, all using annotation configuration.

Other interesting posts you may like

Let’s begin step by step with the Spring MVC Hibernate Mysql integration CRUD example tutorial.

Project structure
In this Spring MVC Hibernate Mysql integration CRUD example tutorial, we will create project using maven with structure like below:

Spring MVC Hibernate Mysql integration CRUD example tutorial

Maven Dependencies
First and foremost, we need to add dependencies in pom.xml that we are using for project, like this:

Let’s deeper:
Firt thing, We are using full annotation configuration so we need to configure this plugin in order to avoid maven failure by using the declaration like below:

Second thing, we will use JSR303 Validation to validate the user input. You can refer to the complete Spring MVC Form Validation Annotation Example post to get more detail.

Third thing, we need to include JSP/Servlet/Jstl dependencies to use servlet api’s and jstl view in source code. But we can set the scope as ‘provided’ for them in pom.xml because containers might already support these libraries.

The rest thing, we don’t forget Spring, Hibernate and Joda-Time dependencies.

Hibernate congfiguration

Let’s dig deeper:
@Configuration marked this class contains bean methods annotated with @Bean producing beans manageable by spring container. In this case, this class takes care hibernate configuration.
@ComponentScan is equivalent to the declaration context:component-scan base-package=”…” in xml, it indicates where spring looks for beans or classes.
@EnableTransactionManagement is equivalent to the declaration Spring’s tx:* XML namespace and enable Spring’s annotation-driven transaction management capability.
@PropertySource is used to declare a set of properties so we can configure different values in different application environments.

Method sessionFactory() is creating a LocalSessionFactoryBean, which is equivalent to the below declaration:

Once the SessionFactory is created, it will be injected into Bean method transactionManager which enable the support of transaction management.

Below is the properties file used in the above code snippet.
/src/main/resources/jdbc.properties

Configure Spring MVC with Java Annotation Configuration
This Spring MVC configuration part was introduced in the previous tutorial, you can refer to the post Spring MVC Annotation Example. So i don’t mention it here. You can also look into the MyWebConfig class in the attachment source code.

In this post, we are working with form submission and validating user input. The “messages” properties file is used to contain messages form warning user. We have a tutorial for this topic, you can refer to the post Spring MVC Form Validation Annotation Example. You can also look into the messages.properties file in attached source code.

Configure the Dispatcher Servlet
This Configure the Dispatcher Servlet part was introduced in the previous tutorial, you can refer to the post Spring MVC Annotation Example. So i don’t mention it here. You can also look into the ServletInitializer class in the attached source code.

Create Controller

Add the controller which will serve the GET and POST request.

Let’s dig deeper:
@Controller annotation marked this MyController class is a controller that handle the requests with pattern ‘/’ mapped by @RequestMapping.

Method listStudents is annotated with @RequestMethod.GET and handle the requests with both pattern ‘/’ and ‘/list’. It takes care for initial page of application, showing a list of existing students

Method newStudent handle the GET request for the new student registration page.

Method saveStudent will handle the form-submission POST requests – pattern ‘/new’ for new student registration. @Valid asks spring framework to validate the associated object(Student) following the JSR303 Validation standard. BindingResult receives the outcome of this validation and any error that might have occurred during this validation. In case of validation failure, error messages will be shown.

Method editStudent brings you to the registration page that is filled up student details, while updateStudent will be invoked when you click on update button.

Method deleteStudent takes care the deletion of an student by CODE. Notice @PathVariable, which bind its parameter to variable in URI template.

The above stuffs are all we need to do for Annotation based configuration. We will add layer, dao layer, views, domain object, database schema and run the application.

Add DAO Layer

This AbstractDao class is the base class for all DAO implementation classes. It provides the wrapper methods for common hibernate operations. Here, we are injecting the SessionFactory that is mentioned in above.

Add Service Layer

Most interesting part above is @Transactional which starts a transaction on each method start, and commits it on each method exit ( or rollback if method was failed due to an error). Note that since the transaction are on method scope, and inside method we are using DAO, DAO method will be executed within same transaction.

Create Entity Class(POJO)

In this Spring MVC Hibernate Mysql integration CRUD example tutorial, we create the actual Student Entity like this:

The above is a standard Entity class annotated with JPA annotations @Entity, @Table, @Column. One more, hibernate specific annotation @Type are using to map between database date type and Joda-Time LocalDate.

@DateTimeFormat is a specific annotation which indicates that a field should be formatted as a date time with a give format.

Rest of annotations are validation related JSR303 API, you also get more about it via the post Spring MVC Form Validation Annotation Example

Add Views

allstudents.jsp is a page that contain list of all existing students

registration.jsp is a registration page to create and save new student

success.jsp is a success page with confirmation of new student creation

Create Schema in database

If MySQL installation is a problem with you, you can search MySQL installation on Local PC on google or download XAMPP that is just packaged with Mysql.

Build, deploy and Run Application
Now we can build war file by using eclipse or maven command line. Since here we are using Tomcat such as Servlet container and we put this war file into tomcat webapps folder then start tomcat. Access the address http://localhost:8080/spring-mvc-hibernate-example and the screen will display like this:

Spring MVC Hibernate Mysql integration CRUD example tutorial

Add new student by clicking the link “Add New Student” and enter information of student, for example:

Spring MVC Hibernate Mysql integration CRUD example tutorial

Then click the Register button to insert student data into database. Back to the “List of All Students” screen, we see that student.

Spring MVC Hibernate Mysql integration CRUD example tutorial

Now we can update the student information that we just register on the above step by clicking the link in the CODE column on the “List of All Students” screen. It brings you to the update screen like this:

Spring MVC Hibernate Mysql integration CRUD example tutorial

Change the entering date and nationality of student and click the update button. Beside, we can delete a student by clicking its delete link.

That’s it on the Spring MVC Hibernate Mysql integration CRUD example tutorial

Downlaod complete source code of example, please click link below

SpringMVCHibernateExample.zip (205 downloads)

2 thoughts on “Spring MVC Hibernate Mysql integration CRUD Example Tutorial

  1. Can you help me fix this error?
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile (default-compile) on project SpringMVCHibernateExample: Compilation failure
    [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

    • Here is common error. Fix this following steps:
      1. On your Eclipse IDE, go into Window > Preferences > Java > Installed JREs > and check your installed JREs. You should have an entry with a JDK there.
      2. Select the Execution Env as show below. Click OK
      3. Then Right-Click on your Project -> Maven -> Update Project

Leave a Comment

*

Please share it if you found this useful
Hide Buttons