Spring Boot Restful Web Services CRUD Example Download - onlyxcodes

Wednesday, 19 February 2020

Spring Boot Restful Web Services CRUD Example Download

In this tutorial, you will see spring boot restful web services crud example with MySQL and JPA. Spring Boot will allow you to set up a tiny configuration in a quick way to create your application. That provides the jar files facility to include your custom jar file packages as well as the built-in Tomcat Server for executing your application, we don't have to include external servers.

Let's start the tutorial we do to build the Spring Restful Web Service CRUD application using JPA.

Spring Boot Restful Web Services CRUD Example Download

Table Content

1. What is CrudRepository Interface

2. The API we’ll build

3. Database and Table Creating

4. Creating New Spring Boot Project

5. pom.xml

6. application.properties

7. Student.java

8. StudentRepository.java

9. StudentController.java

10. SpringBootRestfulCrudApplication.java

11. Let’s the test application


What is CrudRepository Interface

CrudRepository is an interface that arrives from Spring Framework. CrudRepository extends Spring Data Repository which is a core marker interface for the repository. CrudRepository offers the formulaic method for the operation of creating, reading, updating, and deleting.

CrudRepository contains a total of 11 CRUD operation methods, some of which are listed below which we will be using in this application:

<S extends T> S save(S entity): Save and update a given entity. The entity must not be null and the saved entity; will never be null.

Iterable<T> findAll(): Returns all entities.

Optional<T> findById(ID id): Retrieves an entity by its ID. The ID must not be null.

void deleteById(ID id): Deletes the entity with the given ID. The ID must not be null.

Note: note took above all methods from docs.spring.io

The API we'll build

We'll create a Student Resource which uses Restful API (URIs) and HTTP methods to consume three services.

URLsMethodDescription
/students/add@PostMappingCreate a new student
/students/all@GettMappingRetrieve all students
/students/student/{id}@GettMappingGet records of a particular student
/students/update/{id}@PuttMappingUpdate existing student records
/students/delete/{id}@DeleteMappingDelete a particular student record

Database and Table Creating

Database Credentials. In this tutorial, I will store the first name and last name of the student. Import the code below into your PHPMyAdmin.

CREATE TABLE `tbl_student` (
  `student_id` int(11) NOT NULL,
  `student_firstname` varchar(15) NOT NULL,
  `student_lastname` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Creating New Spring Boot Project

Note: You must have an enabled internet connection.

Step 1 Start Spring Too Suite. Go to File -> New -> Spring Starter Project. Choose Spring Starter Project according to the figure below.

Start Spring Too Suite. Go to File -> New -> Spring Starter Project.

Step 2 In the second step, the configuration of the project is typed below. Click on the next button after fill-up.

Name – SpringBootRestfulCRUD

Group – com.onlyxcodes

Description – Spring Boot Restful CRUD JPA and MySQL

Package – com.onlyxcodes.app

configuration of the spring boot project. Fill-up name, group and description

Step 3 – In the third step select packages with custom jar files. MySQL Driver, Spring Data JPA, and Spring Web. Click the next button below.

select packages with custom jar files.

Step 4 – Finally, the last step is to set up a project. Select the Finish button.

last step to set up a project.

See below complete project directory structure.

Project directory structure of Spring Boot Restful Web Service CRUD example in STS tool

pom.xml

To build Spring Boot Restful CRUD application by following necessary dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.2.4.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.onlyxcodes</groupId>
 <artifactId>SpringBootRestfulCRUD</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringBootRestfulCRUD</name>
 <description>Spring Boot Restful CRUD JPA MySQL</description>

 <properties>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
   <exclusions>
    <exclusion>
     <groupId>org.junit.vintage</groupId>
     <artifactId>junit-vintage-engine</artifactId>
    </exclusion>
   </exclusions>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>

application.properties

To connect the MySQL database and set up a configuration of JPA properties by following the codes. Inside src/main/resources/application.properties we will import these codes.

# MySQL database connecting utility
spring.datasource.url=jdbc:mysql://localhost:3306/springbootrestcrud_db
spring.datasource.username=root
spring.datasource.password=

# JPA property utility
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.show_sql=true

Settings properties elements (spring.datasource.*) in the application.properties file offer the DataSource configuration.


With the help of the properties configuration, the application code and configuration are separated. We can import data source configurations in this manner from systems that are configuration provider systems.


The properties of the MySQL database are shown in the setup above.


spring.datasource.url=jdbc:mysql://localhost:3306/springbootrestcrud_db :- Your database's location is indicated by the url. You're indicating that my database may be found at http://localhost:3306/springbootrestcrud_db, where springbootrestcrud_db is the name of the database.


spring.datasource.username=root:- The database username is the root.


spring.datasource.password=:- This shows the password for the database. Since there is no password in my database, I left this blank.


spring.jpa.hibernate.ddl-auto:- This is a Hibernate feature that more precisely regulates the behavior. For more on the upgrade, see below.


Update: After comparing the generated object model (annotations or XML) with the current schema, Hibernate modifies the schema by the differences. Even if the program no longer needs the existing tables or columns, it never deletes them.


spring.jpa.properties.hibernate.show_sql=true:- The following hibernate property can be set up to format the output SQL from JPA.


Create JPA Entity or Model class

Student.java

In the com.onlyxcodes.app.model package, create a Student model class. We describe five attributes for the annotation in this class.

@Entity and @Table establish top of class annotation. @Entity proves that the class is a persistent Java class and @Table annotation used to map your existing database table.

@Id use primary key annotation. @GeneratedValue annotation can be used to specify the primary key generation strategy. GenerationType.AUTO, the default generation type AUTO that the table field auto Increment. @Coulmn annotation used to map columns from the table.

Note: If your database doesn't have a table, @Entity annotation informs Hibernate to create a table out of that class.

package com.onlyxcodes.app.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tbl_student")
public class Student {
 
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "student_id")
 private int id;
 
 @Column(name = "student_firstname")
 private String firstname;
 
 @Column(name = "student_lastname")
 private String lastname;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 public String getLastname() {
  return lastname;
 }

 public void setLastname(String lastname) {
  this.lastname = lastname;
 }
 
}

Create Repository Interface

StudentRepository.java

Create a StudentRepository interface underneath in com.onlyxcodes.app.repository package. And extends CrudRepository which Spring Boot implemented auto into a Bean called a studentrepository.

After that, we must construct a fundamental repository layer that enables us to carry out CRUD operations on members of the above Student entity class.


We don't need to start from scratch with our own DAO implementation because Spring Data JPA is what we're utilizing. To create a functional repository implementation, we only need to extend the CrudRepository interface:


In our example, the model is Student and the ID type is Integer, and the CrudRespository interface accepts both.


package com.onlyxcodes.app.repository;

import org.springframework.data.repository.CrudRepository;

import com.onlyxcodes.app.model.Student;

public interface StudentRepository extends CrudRepository<Student, Integer>{

}

Create the Controller

StudentController.java

Finally, inside the package com.onlyxcodes.app.controller creates StudentController class. This class handles the user-desired operation of creating, reading, updating, and deleting.

package com.onlyxcodes.app.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.onlyxcodes.app.model.Student;
import com.onlyxcodes.app.repository.StudentRepository;

@RestController
@RequestMapping("students")
public class StudentController {

 @Autowired
 StudentRepository studentrepository;
 
 // retrieve all student from database
 @GetMapping("all")
 public List<Student> getAllStudent()
 {
  List<Student> student=(List<Student>) studentrepository.findAll(); 
  return student;
 }
 
 // insert new student into database
 @PostMapping("add")
 public Student addStudent(@RequestBody Student student)
 {
  return studentrepository.save(student);
 }
 
 // get particular student by their ID
 @GetMapping("student/{id}")
 public Optional<Student> getStudentId(@PathVariable int id)
 {
  return studentrepository.findById(id);
 }
 
 // update existing student 
 @PutMapping("update/{id}")
 public Student updateStudent(@RequestBody Student student)
 {
  return studentrepository.save(student);
 }
 
 // delete particular student from database
 @DeleteMapping("delete/{id}")
 public void deleteStudent(@PathVariable int id)
 {
  studentrepository.deleteById(id);
 }
}

@RequestMapping("/students") specifies that in this controller the URL of the REST API must begin with /students, so that we can use http://localhost:8080/students as our endpoint.

We use @Autowired for StudentRepository Interface class object injection.

The annotation @RequestBody indicates that a method parameter will be attached to the body of the web request. That means the method expects the following information in JSON format from the submission.

In spring the @PathVariable annotation binds the URI template variables to a controller's handler method parameters. A URI template contains the following variables of one or more paths enclosed by braces ({ }).

Note: the name of the template variable (between the curly braces) and the name of the parameter should match up.

The @RestController annotation contains the @Controller  and @ResponseBody  annotations. The @Controller  annotation represents a class with endpoints and the @ResponseBody  indicates a method return value should be bound to the web response body (according to documentation ).

The annotation @GetMapping denotes that a GET request is processed by the method.


An annotation called @PostMapping indicates that a function handles a POST request.


The annotation @PutMapping shows that a function handles a PUT request.


The annotation @DeleteMapping indicates that a method handles a DELETE request.


SpringBootRestfulCrudApplication.java

See our application executing App Class.

package com.onlyxcodes.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRestfulCrudApplication {

 public static void main(String[] args) {
  SpringApplication.run(SpringBootRestfulCrudApplication.class, args);
 }

}

Let's the test application

Now all of the codes are done perfectly. Let's check this application in the Postman. Friends this tool is also available on the Google Chrome extension.

1. Create a new Student.

First, by adding a new student to this URL http://localhost:8080/students/ add, select the POST method, select the raw radio button in the Body tab, set Content-Type="application/json" in the Headers tab, and paste the following JSON code.

Note: If you want to insert a new record, we don't need to type the Id number because Hibernate automatically generates the sequence number in the database.

{
    "firstname": "hamid",
    "lastname": "shaikh"
}

Create a new Student record in postman tool

See also record created in a database table.

check record created in a database table.



2. Read student record

By this URL http://localhost:8080/students/all, we retrieve student record. Choose the GET method, and click the Send button.

Read student record in postman tool



3. Update student record

We update the existing student record using this URL http://localhost:8080/students/update/1, select the PUT method, select the raw radio button in the Body tab, set Content-Type="application/json" in the Headers tab, and then paste the following JSON code.

Note: URL end 1 is your table Id. Since I change the record of 1 Id number.

{
    "id": 1,
    "firstname": "ankit",
    "lastname": "patel"
}

update the existing student record in postman tool

See also the updating of I d 1 record on the table

check record updating on table



4. Delete student record

Finally, with this URL http://localhost:8080/students/delete/1 we delete the student record, select the DELETE method and click the send button.

Note: Your table Id is the end of URL 1 Because I want to delete the record of 1 Id number.

Delete student record in postman tool

On the table, too, the record was removed.

check record deleted in table

I hope you are enjoying Spring Boot Restful Web Service CRUD example Happy Coding :)

Related Articles –


Sending Email using Spring Boot Rest API


Spring Boot MVC CRUD Example With MySQL


Consuming (CRUD) Restful Web Service in Java


Download Codes

No comments:

Post a Comment

Post Bottom Ad