Spring MVC Data JPA Hibernate
Spring MVC 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
1 <properties>
2 <spring.version>5.1.5.RELEASE</spring.version>
3 <hibernate.version>5.4.1.Final</hibernate.version>
4 </properties>
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>
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.
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.
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
- @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.
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>
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.
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
Page | 13
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.
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.
Click the Delete link next to a customer in the home page, it will be deleted and the list is refreshed.
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: