Spring Boot and MySQL: Simple CRUD Application (REST Api) with Spring Data JPA

 

Today i am going to explain how to develop simple CRUD (Create,Retrieve,Update and Delete data) application with Spring Boot and  Spring Data JPA.  the application will be simple web application and which will expose few REST endpoints for CRUD related operations.

 

What is Spring Data JPA?

Spring Data JPA is a sub project that comes under the Spring Data project and it is under the umbrella/shelter of Spring family.  This will implements the JPA (Java Persistence Api) specification and have classes and methods for accessing and managing the data tier of the application. It tries to simplify the complexity associated with the data access layer of the application.  As i have already mentioned, Spring Data JPA  has following objectives.

  • provides a better implementation for the JPA Specification.
  • avoid the complexity associated with the Data Access layer of the application (by providing a framework that is easy to implement and  having robust features)

 

So it is enough with theories. lets explore and play with the framework.  As usual.  i have used the https://start.spring.io/  for generating the project.

Screen Shot 2017-12-30 at 7.30.47 PM.png

As you can see in the generation wizard, we are using two dependencies other than web dependency. That is JPA and MySQL.

JPA – Represents the maven dependency for Spring Data JPA.

MySQL – Represents the maven dependency for mysql-jdbc-connector 

 

So Lets Open the pom.xml file and look at the dependency section for identifying those dependencies.

<dependencies>
<!–Spring Data JPA Dependency–>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!–Spring Web Dependency–>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!–MySQL JDBC Connector –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>

view raw
pom.xml
hosted with ❤ by GitHub

 

What we are going to build?

We will do CRUD related operations with a user object and ultimately we will build a REST api application with four endpoints  for CRUD related operations.

  • HTTP POST    /api/users   For creating the user
  • HTTP PUT     /api/users   For updating the user
  • HTTP DELETE    /api/users/:user_id   For deleting the user
  • HTTP GET    /api/users   For retrieving all the users

 

Where do we start?

Spring Data JPA is all about creating Entities and Repositories.

Entity lives in between java object (java class) and relational table. It helps to map the java object to relational table and relational table back to java object.

Repository helps to perform CRUD related operations with Entity.

The actual definition of Entity and Repository might be different from the explanation that i have given. Basically i just wanted to simply point out the exact purpose/role of Entity and Repository.

So Lets create our Entity and Repository.

 

Creating the Entity

The Entity class will be the following class.

import javax.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String country;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

view raw
User.java
hosted with ❤ by GitHub

 

Things to Remember

The most important thing that you should note here is that we have used java persistence api (JPA annotations) based annotation here. No any framework specific annotation used. This is to compatible with other JPA implemented/supported ORM frameworks. For instance, if you have developed the data layer to compliant/adherent with JPA specification, then it will be possible to switch with different JPA implementations with minimal effort.

 

Creating the Repository

Creating a JPA based repository is very simple. You have to create an interface that extends the JpaRepository interface by providing the generic parameter, the Entity class and ID type.  Here is the sample code for implementing UserRepository.

import com.springbootdev.domain.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long>
{
}

view raw
UserRepository.java
hosted with ❤ by GitHub

User – is the entity class

Long – is the data type of the ID (Primary Key).

All the methods required for the CRUD related operations will be inherited from the super level/parent interfaces. Therefore we do not have to explicitly add or implement CRUD related methods.

Now we have created both Entity class and Repository. Next step is to configure/provide the mysql connection details. It can be provided in the application.properties file.

## Spring DATA SOURCE Configurations
spring.datasource.url = jdbc:mysql://localhost:3306/spring_examples_db?useSSL=false
spring.datasource.username = root
spring.datasource.password = test123
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

This will try to connect to the database  “spring_examples_db” running on local mysql server “localhost”  on port “3306”  by providing the username “root” and password “test123“.  You should change these properties based on your mysql server details.

 

Now we should implement our REST endpoints for creating, updating, removing and listing users etc…. Please refer the below UserController.

import com.springbootdev.examples.entity.User;
import com.springbootdev.examples.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/users")
public User create(@RequestBody User user)
{
return userRepository.save(user);
}
@GetMapping("/users")
public List<User> findAll()
{
return userRepository.findAll();
}
@PutMapping("/users/{user_id}")
public User update(@PathVariable("user_id") Long userId, @RequestBody User userObject)
{
User user = userRepository.findOne(userId);
user.setName(userObject.getName());
user.setCountry(userObject.getCountry());
return userRepository.save(user);
}
@DeleteMapping("/users/{user_id}")
public List<User> delete(@PathVariable("user_id") Long userId)
{
userRepository.delete(userId);
return userRepository.findAll();
}
@GetMapping("/users/{user_id}")
public User findByUserId(@PathVariable("user_id") Long userId)
{
return userRepository.findOne(userId);
}
}

view raw
UserController.java
hosted with ❤ by GitHub

 

Creating the User

POST     /api/users

Here is the sample postman request and response.

Screen Shot 2017-12-31 at 11.37.01 AM.png

 

 @PostMapping("/users")
 public User create(@RequestBody User user)
 {
      return userRepository.save(user);
 }

 

@RequestBody – The body of the HTTP request will be mapped to the User class.

@ResponseBody – The retuned object will be mapped to the body of the HTTP response.

 

Retrieving all the users

GET  /api/users

Screen Shot 2017-12-31 at 11.47.03 AM.png

 

 

Retrieving a specific User/Resource

GET  /api/users/{user_id}

 

Screen Shot 2017-12-31 at 11.48.44 AM.png

 

Updating a Specific  User/Resource

PUT  /api/users/{user_id}

 

Screen Shot 2017-12-31 at 11.50.05 AM.png

 

Removing a Specific User/Resource

DELETE  /api/users/{user_id}

 

Screen Shot 2017-12-31 at 12.02.25 PM.png

Once the requested resource is successfully removed, it will return a list of available users.

Ok. we have completed all the REST endpoints for managing users with Spring Data JPA.

Finally we will look at the Spring Boot main configuration class.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDataJpaExampleApplication
{
public static void main(String[] args)
{
SpringApplication.run(SpringBootDataJpaExampleApplication.class, args);
}
}

The configuration class is very simple and we have fully utilized the advantages of spring boot and no additional configurations have been made. We have taken fully advantage of spring boot auto configuration feature.

 

Why didn’t we use @EntityScan or @EnableJpaRepositories annotations here?

The package that contains the main Spring Boot Application configuration class (that is annotated with @SpringBootApplication) is known as the main application package.

If the entity classes and repository classes are placed under the spring boot main application package or its sub package, the spring boot will take care of detecting and scanning of entities and repositories.  In such case wed do not have to explicitly declare the packages of Entities and Repositories with @EntityScan and @EnableJpaRepositories annotations respectively.

Please refer the below project structure.

Screen Shot 2017-12-31 at 12.30.41 PM.png

If you look at the project file structure, you can notice that entity and repository packages are sub packages of the main application package. Therefore the entities and repositories placed under those packages will be automatically scanned and detected when the spring boot application is loaded.

If you want to know more about @EntityScan and @EnableJpaRepositories annotations, please go my article publish on that.

 

The full source code of this article can be found at GitHub.

Click here to Download The Source Code.

 

Build and Running the application

 

Build the application

mvn clean install -DskipTests

 

Run The application

java -jar target/spring-boot-data-jpa-example-0.0.1-SNAPSHOT.jar

 

Hope this article is helpful for you.

Thanks

Chathuranga Tennakoon

 

4 thoughts on “Spring Boot and MySQL: Simple CRUD Application (REST Api) with Spring Data JPA

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s