Spring Boot RESTful CRUD API Using JPA Data, Hibernate, MySQL.

Spring Boot RESTful CRUD API Using JPA Data, Hibernate, MySQL

Project Structure

Here is the updated project structure. We will continue with our previous example.

Updated Project Structure


Add Dependencies

First we need to add the following dependencies in our build.gradle file:
  • spring-boot-starter-data-jpa
  • mysql-connector-java
  • spring-boot-starter-data-rest

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa
compile ('org.springframework.boot:spring-boot-starter-data-jpa')
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-rest
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-rest', version: '1.0.0.RELEASE'

Create MySQL Database

Here is the script for mysql data base.

CREATE DATABASE studentdb;



CREATE TABLE Students (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
);

INSERT INTO Students(firstname,lastname,email) 
VALUES ('Yasir','Hussain','yasir.hussain@email.com');
INSERT INTO Students(firstname,lastname,email) 
VALUES ('Shahid','Mustafa','shahid.mustafa@email.com');
INSERT INTO Students(firstname,lastname,email) 
VALUES ('Naveed','Rehman','naveed.rehman@email.com');

Configure Data Source

Now we need to configure data source for our project. Add the following code in application.properties

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:mysql://localhost:3306/studentdb
spring.datasource.username=user
spring.datasource.password=pass
## Hibernate Properties# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update

Create An Entity

@Entity@Table(name = "Students")
public class Student {

    @Id    @Column(name = "id")
    private long id;

    @Column(name = "firstname")
    private String firstName;

    @Column(name = "lastname")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Column(name = "reg_date")
    private Date regDate;
}
Note : You need to create getter and setter here which is not mention here.

Create a Repository

@RepositoryRestResourcepublic interface StudentRepository extends JpaRepository<Student, Long> {
}



Create a REST Controller

@RestControllerpublic class StudentController {

    @Autowired    StudentRepository studentRepository;

    // create    @RequestMapping(value = "/student", method = RequestMethod.POST)
    public Student createStudent(@RequestBody Student student){
        return studentRepository.save(student);
    }

    // read by id    @RequestMapping(value = "/student/{id}", method = RequestMethod.GET)
    public Optional<Student> getStudentById(@PathVariable Long id){
        return studentRepository.findById(id);
    }

    // read all    @RequestMapping(value = "/students", method = RequestMethod.GET)
    public List<Student> getAllStudents(){
        return (List)studentRepository.findAll();
    }

    // update    @RequestMapping(value = "/student", method = RequestMethod.PUT)
    public Student updateStudent(@RequestBody Student student){
        return studentRepository.save(student);
    }

    // delete by id    @RequestMapping(value = "/student/{id}", method = RequestMethod.DELETE)
    public void deleteStudentById(@PathVariable Long id){
         studentRepository.deleteById(id);
    }
}

Now our project is complete. We are using Postman to test our Spring Boot RESTful CRUD Api.

Get Request (for Fetch All Students)

GET Request for getting all students

POST Request (for a New Student Record)

POST Request for create a student record
In Response Body, we received Student Object.

GET Request (Fetch a Student Record By Its ID)

GET Request for fetch a Student's record by its id

PUT Request (Update a Student's Record)

PUT Request for update the Student's record

GET Request (Fetch all Students)

GET Request for getting all students record
DELETE Request (Delete a Student Record by its ID)

DELETE Request for delete a student record by its id

Now this time there is noting in response body because delete request method does not retuen anything in our RestController. Now just need to verify this we hit again the getAllStudents endpoint.

Get Request (for Fetch All Students)

GET Request for fetch all students record

We successfully test all the endpoints and its working fine. In our next post, we try to make UI for this Spring Boot RESTful CRUD Web Service by using AngularJS. Just stay tuned.

Comments

Popular posts from this blog

How To Run Spring Boot Web Application On External Tomcat

Spring Boot v.2.0.2 Release Hello World Example

Basic CRUD Application Using Spring Boot REST Web Service with AngularJS