Sunday, 11 March 2018

Spring Boot Rest service with spring jdbc

Hi Friends,I am going to introduce Rest Service using Spring Boot.

Following technology being used:
1)Spring Boot 1.4.1.RELEASE
2)Spring 4.0
3)Maven 4.0
4)JDK 1.7

Project Structure:


Dependency Management:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>org.demo</groupId>
 <artifactId>test</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootHelloWorld</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.1.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>

Typical Spring boot application is as given below :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package org.main;

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

@EnableAutoConfiguration
@SpringBootApplication(scanBasePackages={"org.test"})
public class main {

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

5 Endpoints are exposed in below rest controller .summary of each is as given below :
Endpoints Description
localhost:8098/student/getAll API that returns all student
localhost:8098/student/get/{id} Api that return student based on id 
localhost:8098/student/add/{id} API that adds student
localhost:8098/student/updte/{id} API that updates student
localhost:8098/student/delete/{id} API that deletes student

Rest Controller :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package org.test.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import org.test.bean.Student;
import org.test.dao.StudentDAOImpl;

@EnableAutoConfiguration
@RestController
public class StudentController {

 @Autowired
 private StudentDAOImpl dao;
 
 @GetMapping("/student/getAll")
 public ResponseEntity<List<Student>> getAllStudents() 
 {
  
 List<Student> listStudents= dao.getAllStudents();
 if(listStudents.size()==0)
  return new ResponseEntity<List<Student>>(HttpStatus.NOT_FOUND);
 
 return new ResponseEntity<List<Student>>(listStudents,HttpStatus.OK);
 }
 @GetMapping("/student/get/{id}")
 public ResponseEntity<Student> getStudent(@PathVariable("id") String id) 
 {
 Student stud = dao.getStudent(id); 
 if(stud==null)
  return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);

 return new ResponseEntity<Student>(stud,HttpStatus.OK);
 
 }
 @PostMapping("/student/add/{id}")
 public ResponseEntity<?> addStudent(@RequestBody Student student, UriComponentsBuilder ucBuilder) 
 {
 Student stud = dao.addStudent(student); 
 if(stud==null)
  return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);
 HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/student/user/{id}").buildAndExpand(student.getId()).toUri());
 return new ResponseEntity<String>(headers,HttpStatus.CREATED);
 
 
 }
 
 @PutMapping("/student/updte/{id}")
 public ResponseEntity<?> updateStudent(@PathVariable("id")String id ,@RequestBody Student student) 
 {
 
 int rowcount=dao.updateStudent(id,student);
 
 if(rowcount==0)
  return new ResponseEntity(new CustomMessage("Unable to upate. Student with id " + id + " not found."),HttpStatus.NOT_FOUND);
 else 
 return new ResponseEntity<Student>(student,HttpStatus.OK);
 
 }
 @DeleteMapping("/student/delete/{id}")
 public ResponseEntity<?> deleteStudent(@PathVariable("id") String id) 
 {
 Student obj = dao.getStudent(id); 
 if(obj==null)
  return new ResponseEntity(new CustomMessage("Unable to delete Student with id " + id + " not found."),HttpStatus.NOT_FOUND);
  

 dao.deleteStudent(id);
 return new ResponseEntity<Student>(HttpStatus.NO_CONTENT); 
 } 
}

DAO layer is given below :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package org.test.dao;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.test.bean.Student;

@Repository
public class StudentDAOImpl {

 @Autowired
 public  JdbcTemplate template;

 public Student addStudent(Student student) {
  // TODO Auto-generated method stub
  
  String sql="insert into student(id,name,college,status) values(?,?,?,'A')"; 
        template.update(sql,new Object[]{student.getId(),student.getName(),student.getCollege()});
  return student;
 }

 public int updateStudent(String id, Student stud) {
  // TODO Auto-generated method stub
        int[] types = {Types.VARCHAR, Types.VARCHAR,Types.VARCHAR};
  String sql = "update student set name = ? ,college =? where id = ?";
  int rows = template.update(sql,new Object[]{stud.getName(),stud.getCollege(),id},types);
  
        System.out.println(rows + " row(s) updated.");        
  return rows;
 }

 public void deleteStudent(String id) {
  String sql="delete from student where id=?";
  template.update(sql,id);  
 }

 public Student getStudent(String id) {
  
  String sql = "SELECT * FROM student WHERE id = ?";

  Student customer = (Student) template.queryForObject(
    sql, new Object[] { id },
    new BeanPropertyRowMapper(Student.class));

  return customer;  
 }

 public List<Student> getAllStudents() {
  String sql = "select * FROM student";

  List<Student> listStudent = new ArrayList<Student>();

  List<Map<String, Object>> rows = template.queryForList(sql);
  for (Map row : rows) {
   Student stud = new Student();
   stud.setId((String)(row.get("id")));
   stud.setName((String)row.get("name"));
   stud.setCollege((String)row.get("college"));
   listStudent.add(stud);
  }

  return listStudent; 
 }
 
}

Test the API:
I will use external client POSTMAN to test the endpoints exposed .

1. Get All Students



2. Get Specific Student


3.Add student : one need to provide request body and content type as "application/json'.


4.Delete Student : No Response in Response body . HttpStatus.NO_CONTENT is returned .



Hope you like this article .for any query ping me on  npjava90@gmail.com

No comments:

Post a Comment

Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...