Skip to main content

how to create rest api using spring boot in eclipse

 how to create rest api using spring boot in eclipse


For Explanation Watch Video:




Directory:





application.properties::


#server port
server.port=3031

#datasource
spring.datasource.url=jdbc:mysql://localhost:3306/new
spring.datasource.username=root
spring.datasource.password=root

#jpa
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create



SpringBootRestApplication 


package com.app;

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

@SpringBootApplication
public class SpringBootRestApplication {

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

}


StudentController 


package com.app.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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.PatchMapping;
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.app.entity.Student;
import com.app.service.IStudentService;

@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private IStudentService service;
//1.save student
@PostMapping("/save")
public ResponseEntity<String> saveStudent(@RequestBody Student std){
ResponseEntity<String> response = null;
//call the service 
Integer id = service.saveStudent(std);
String msg  = "Student with id '"+id+"' is saved";
response = new ResponseEntity<String>(msg,HttpStatus.OK);
return response;
}
//2.get all student
@GetMapping("/all")
public ResponseEntity<List<Student>> getAll(){
ResponseEntity<List<Student>> response = null;
//call the service
List<Student> list = service.getAllStudents();
response = new ResponseEntity<List<Student>>(list,HttpStatus.OK);
return response;
}
//3.get One student
@GetMapping("/get/{sid}")
public ResponseEntity<Student> getOneStudent(@PathVariable Integer sid){
ResponseEntity<Student> response = null;
//call the service
Student std = service.getStudentById(sid);
response = new ResponseEntity<Student>(std,HttpStatus.OK);
return response;
}
//4.update student
@PutMapping("/update")
public ResponseEntity<String> updateStudent(@RequestBody Student std){
ResponseEntity<String> response = null;
//call the service
service.updateStudent(std);
String msg = "Student Updated";
response = new ResponseEntity<String>(msg,HttpStatus.OK);
return response;
}
//5.delete student by id
@DeleteMapping("/delete/{sid}")
public ResponseEntity<String> deleteOneStudent(@PathVariable Integer sid){
ResponseEntity<String> response = null;
//call the service
service.deleteStudentById(sid);
String msg = "Student Deleted";
response = new ResponseEntity<String>(msg,HttpStatus.OK);
return response;
}
//6.partial update
@PatchMapping("/modify/{sid}/{add}")
public ResponseEntity<String> updateStudentAddress(
@PathVariable Integer sid
,@PathVariable String add){
ResponseEntity<String> response = null;
//call the service
service.updateStudentAdd(sid, add);
String msg = "Student address with id '"+sid+"' updated";
response = new ResponseEntity<String>(msg,HttpStatus.OK);
return response;
}
}


Student 


package com.app.entity;

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

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "stutab")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "sid")
private Integer studentId;
@Column(name = "sname")
private String studentName;
@Column(name = "sadd")
private String studentAddresss;
@Column(name = "avg")
private Double studentAvg;
}


StudentRepository 


package com.app.repo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import com.app.entity.Student;

public interface StudentRepository extends JpaRepository<Student, Integer>{
@Modifying//non-select
@Query("UPDATE Student SET studentAddresss=:add WHERE studentId=:id")
Integer updateStudentAddById(Integer id,String add);
}


IStudentService 



package com.app.service;

import java.util.List;

import com.app.entity.Student;

public interface IStudentService {
//1.save student
Integer saveStudent(Student std);
//2.get all student
List<Student> getAllStudents();
//3.get student by id
Student getStudentById(Integer id);
//4.delete student by id
void deleteStudentById(Integer id);
//5.update
void updateStudent(Student std);
//6.partial update
Integer updateStudentAdd(Integer sid,String add);
}


StudentServiceImpl 


package com.app.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.entity.Student;
import com.app.repo.StudentRepository;
import com.app.service.IStudentService;

@Service
public class StudentServiceImpl implements IStudentService{

@Autowired
private StudentRepository repo;
@Override
public Integer saveStudent(Student std) {
std = repo.save(std);
return std.getStudentId();
}

@Override
public List<Student> getAllStudents() {
return repo.findAll();
}

@Override
public Student getStudentById(Integer id) {
Optional<Student> opt = repo.findById(id);
if(opt.isEmpty()) {
return null;
}
return opt.get();
}

@Override
public void deleteStudentById(Integer id) {
repo.deleteById(id);
}

@Override
public void updateStudent(Student std) {
repo.save(std);
}

@Transactional
public Integer updateStudentAdd(Integer sid, String add) {
// TODO Auto-generated method stub
return repo.updateStudentAddById(sid, add);
}

}




Comments

Popular posts from this blog

Servlet Project Book Shop Application in eclipse

 Servlet Project Book Shop Application in eclipse  For explanation watch video::: Note :: In this Project you must configure web server (for example tomcat) with eclipse ide Download Bootstrap  from ::         https://getbootstrap.com/docs/4.3/getting-started/download/ Download mysql jar file from :: https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.22 adding MySQL Connector/J jar file in eclipse ide for jdbc video :: video link : https://youtu.be/4Fyd-k3eG_I Directory Structure:: web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">   <welcome-file-list>     <welcome-file>home.html</welcome-file>   </welcome-file-list>   <display-...

JDBC basic example For Select Query

JDBC basic example For Select Query  For explanation watch video:  For Creating Table:: SQL> create table emp60(srno int,fname varchar2(10)); Table created. SQL> desc emp60;  Name                                      Null?    Type  ----------------------------------------- -------- ----------------------------  SRNO                                               NUMBER(38)  FNAME                                              VARCHAR2(10) SQL> insert into emp60 values(1,'allu'); 1 row created. SQL> insert into emp60 values(2,'vijay'); 1 row created. SQL> insert into emp60 values(3,'rajni'); 1 row created. SQL...

JDBC Program to access table data from mysql database

 import java.sql.*; class MysqlCon  { public static void main(String[] args)  { try{ Connection con = DriverManager.getConnection("jdbc:mysql:///new","root","root"); Statement st = con.createStatement(); String query = "select * from login"; ResultSet rs = st.executeQuery(query); while(rs.next()){ System.out.println(rs.getString(1)+" "+rs.getString(2)); } con.close(); }catch(SQLException e){ System.out.println("Error"); }catch(Exception e){ } } }