0% found this document useful (0 votes)
320 views19 pages

Spring MVC Data JPA Hibernate

This document provides instructions for creating a Spring MVC web application using Spring Data JPA and Hibernate to perform CRUD operations on a MySQL database. It describes creating the database, setting up the project structure in Eclipse, configuring Spring and JPA, implementing the model, repository, and service classes, and adding controllers to handle requests. The application allows listing, creating, editing, and deleting customer records from the database without writing any DAO code thanks to Spring Data JPA.

Uploaded by

darwinvargas2011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
320 views19 pages

Spring MVC Data JPA Hibernate

This document provides instructions for creating a Spring MVC web application using Spring Data JPA and Hibernate to perform CRUD operations on a MySQL database. It describes creating the database, setting up the project structure in Eclipse, configuring Spring and JPA, implementing the model, repository, and service classes, and adding controllers to handle requests. The application allows listing, creating, editing, and deleting customer records from the database without writing any DAO code thanks to Spring Data JPA.

Uploaded by

darwinvargas2011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Spring MVC + Spring Data JPA + Hibernate -

CRUD Example
By completing this tutorial, you will be able to create a Java web application powered by SpringMVC-
Spring Data JPA that looks like this: Page | 1

The software programs and technologies used in this tutorial are: Java 8, Apache Tomcat 9, MySQL
Server 5.7, Eclipse IDE 4.7 (Oxygen), Spring framework 5.1, Hibernate framework 5.4, Spring Data
JPA 2.1.5 and Servlet 3.1.
Here's the table of content:
1. Create Database
2. Create Project in Eclipse
3. Create JPA Configuration File
4. Code Model Class
5. Code Configuration Classes
6. Code Respository Interface
7. Code Service Class
8. Code Spring MVC Controller Class
9. Code List Customer Feature
10. Code Create New Customer Feature
11. Code Edit Customer Feature
12. Code Delete Customer Feature
13. Code Search Customer Feature
1. Create Database
We use MySQL database. The sample application will manage data in a table
named customer which is in the schema named sales. The table customer has 4
fields: id, name, email and address:

You can execute the following MySQL script to create the database schema and table: Page | 2

CREATE DATABASE `sales`;


CREATE TABLE `customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`address` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ;
Note: Using XAmpp

2. Create Project in Eclipse


Create a Dynamic Web Project in Eclipse, and convert it to Maven project: right-click on the project,
select Configure > Convert to Maven Project. The Create new POM dialog appears. Enter the
following information:
- Group Id: net.codejava
- Artifact Id: CustomerManager
Make sure that the JRE version for the project is Java 8 or newer.
Next, open the Maven's project file pom.xml to configure the dependencies for the project. Declare
properties for the version of Spring and Hibernate frameworks:

1 <properties>
2 <spring.version>5.1.5.RELEASE</spring.version>

3 <hibernate.version>5.4.1.Final</hibernate.version>

4 </properties>

Specify the following dependency for the core of Spring framework:

1 <dependency>
2 <groupId>org.springframework</groupId>

3 <artifactId>spring-context</artifactId>

4 <version>${spring.version}</version>

</dependency>
5
For web development with Spring MVC:

1 <dependency>
2 <groupId>org.springframework</groupId>

3 <artifactId>spring-webmvc</artifactId> Page | 3
4 <version>${spring.version}</version>

</dependency>
5
To use Spring Data JPA, we need to specify the following dependencies:

1
<dependency>
2
<groupId>org.springframework</groupId>
3 <artifactId>spring-orm</artifactId>
4 <version>${spring.version}</version>
5 </dependency>

6 <dependency>

7 <groupId>org.springframework.data</groupId>

<artifactId>spring-data-jpa</artifactId>
8
<version>2.1.5.RELEASE</version>
9
</dependency>
10
We use Hibernate as a provider of JPA, so add the following dependency:

1 <dependency>
2 <groupId>org.hibernate</groupId>

3 <artifactId>hibernate-core</artifactId>

4 <version>${hibernate.version}</version>

</dependency>
5

To let the application work with MySQL database, we need to have the dependecy for MySQL JDBC
driver:

1 <dependency>

2 <groupId>mysql</groupId>

3 <artifactId>mysql-connector-java</artifactId>

4 <version>8.0.14</version>
5 <scope>runtime</scope>

6 </dependency>

And for Java Servlet, JSP and JSTL:

1 Page | 4
<dependency>
2
<groupId>javax.servlet</groupId>
3
<artifactId>javax.servlet-api</artifactId>
4
<version>3.1.0</version>
5
<scope>provided</scope>
6
</dependency>
7 <dependency>
8 <groupId>javax.servlet.jsp</groupId>

9 <artifactId>javax.servlet.jsp-api</artifactId>

10 <version>2.3.1</version>

<scope>provided</scope>
11
</dependency>
12
<dependency>
13
<groupId>jstl</groupId>
14
<artifactId>jstl</artifactId>
15
<version>1.2</version>
16 </dependency>
17
You can see the complete code of the pom.xml file in the sample project attached along this tutorial.

Create two Java packages under the source folder:


- net.codejava.config: for configuration classes.
- net.codejava.customer: for application-specific classes.
3. Create JPA Configuration File
Since JPA is used, we need to specify database connection properties in the persistence.xml file
instead of hibernate.cfg.xml file. Create a new directory named META-INF in the source folder
to put the persistence.xml file as follows:
Page | 5

And write XML code for the persistence.xml file like this:

As you can see, we specify database connection properties such as URL, user, password
and JDBC driver class. Note that the persistence unit name SalesDB will be used in the
configuration code.
4. Code Model Class
Create the domain class Customer to map with the table customer in the database as following:

Page | 6

As you can see, we use the annotation @Entity to map this class to the table customer (the class
has same name as the table). All the class' field names are also identical to the table's ones. The
field id is annotated with @Id and @GeneratedValue annotations to indicate that this field is
primary key and its value is auto generated.
5. Code Configuration Classes
Next, let's write some Java code to configure Spring MVC and Spring Data JPA. We use Java-based
configuration as it's simpler than XML.

Configure Spring Dispatcher Servlet:


Page | 7
To use Spring MVC for our Java web application, we need to register the Spring Dispatcher Servlet
upon application's startup by coding the following class:

The onStartup() method of this class will be automatically invoked by the servlet container when
the application is being loaded. The Spring Dispatcher Servlet handles all the requests via the URL
mapping "/" and it looks for configuration in the WebMvcConfig class, which is described below.
Configure Spring MVC:
Create the WebMvcConfig class under the net.codejava.config package with the following
code:

Page | 8

This class is annotated with the @Configuration annotation to tell Spring framework that this is a
configuration class. The @ComponentScan annotation tells Spring to scan for configuration classes
in the net.codejava package.

In this class, we simply create a view resolver bean that specifies the prefix and suffix for view files.
So create the directory views under WebContent/WEB-INF directory to store JSP files.
You can add more Spring MVC configurations here.
Configure Spring Data JPA:
To enable Spring Data JPA, we need to create two
beans: EntityManagerFactory and JpaTransactionManager. So create another configuration
class named JpaConfig with the following code:

Page | 9

Here, two important annotations are used:

- @EnableJpaRepositories: this tells Spring Data JPA to look for repository classes in the
specified package (net.codejava) in order to inject relevant code at runtime.

- @EnableTransactionManagement: this tells Spring Data JPA to generate code for


transaction management at runtime.

In this class, the first method creates an instance of EntityManagerFactory to manage the
persistence unit SalesDB (this name is specified in the persistence.xml file above).
And the last method creates an instance of JpaTransactionManagerfor
the EntityManagerFactory created by the first method.
That's the minimum required configuration for using Spring Data JPA.
6. Code Respository Interface
Next, create the CustomerRepository interface that extends the CrudRepository interface
defined by Spring Data JPA with the following code:

Page | 10

You see, this is almost the code we need for the data access layer. Deadly simple, right? As with
Spring Data JPA, you don't have to write any DAO code. Just declare an interface that extends
the CrudRepository interface, which defines CRUD methods
like save(), findAll(), findById(),deleteById(), etc. At runtime, Spring Data JPA
automatically generates the implementation code.

Note that we must specify the type of the model class and type of the primary key field when
extending the CrudRepository interface: CrudRepository<Customer, Long>

7. Code Service Class


Next, code the CustomerService class in the business/service layer with the following code:
Note that this class is annotated with the @Transactional annotation so all of its methods will be
intercepted by Spring Data JPA for transaction management. And an instance
of CustomerRepository interface will be injected into this class:

Page | 11

This is like magic, as we don't write any DAO code but Spring Data JPA will generate an
implementation automatically at runtime.

And as you can see, all the methods in this class are for CRUD operations. It simply delegates all
the call to a CustomerRepositoryobject. This class seems to be redundant, but it is needed to
decouple the business/service layer from the repository/DAO layer.

8. Code Spring MVC Controller Class


Next, in the controller layer, create the CustomerController class to handle all requests from the
clients with the following code:

This is a typical Spring MVC controller class, which is annotated with the @Controller annotation.
You can see an instance of CustomerService is injected into this class using
the @Autowired annotation.

We will write code for the handler methods in the following sections.
9. Code List Customer Feature
The application's home page displays all customers, so add the following handler method to
the CustomerController class:

Page | 12

And code the view page (index.jsp) as follows:


Now you can run the website application. Add some rows in the table customer and access the
URL http://localhost:8080/CustomerManager/, you should see something like this:

Page | 13

10. Code Create New Customer Feature


To implement the create new customer feature, we need to write two handler methods. The first one
is to display the new customer form:
And write code for the JSP page new_customer.jsp as follows:

Page | 14
Click the link New Customer in the home page, you should see the new customer form looks like
this:

Page | 15

And the second handler method is to handle the Save button on this form:

As you can see, it will redirect the client to the home page after the customer has been saved
successfully.

11. Code Edit Customer Feature


To implement the edit/update customer feature, add the following handler method to
the CustomerController class:
This method will show the Edit customer form, so code the edit_customer.jsp file as follows:

Page | 16
Click the Edit hyperlink next to a customer in the home page, the edit customer form should appear
like this:

Page | 17

The handler method for the Save button is still the saveCustomer() method.

12. Code Delete Customer Feature


To implement the delete customer feature, add the following code to
the CustomerController class:

Click the Delete link next to a customer in the home page, it will be deleted and the list is refreshed.

13. Code Search Customer Feature


Finally, let's implement the search feature that allows the user to search for customers by typing a
keyword. The search function looks for matching keywords in either three fields name, email or
address so we need to write a custom method in the CustomerRepository interface like this:
You see, the search()method is just an abstract method annotated with the @Query annotation.
The search query is JPA query.

Then, add the following method in the CustomerService class:


Page | 18

Implement the handler method in the controller class as follows:

And write code for the search result page as follows:


To test the search function, type a keyword into the search box in the home page, and hit Enter. You
should see the search result page looks like this:

Page | 19

That's how to develop a Spring MVC web application using Spring Data JPA for the data access
layer. You've seen Spring Data JPA greatly simplifies the code we need to write.
For your reference, here's the final structure of the project in Eclipse IDE:

You might also like