06jan23-Springboot-Student CRUD
06jan23-Springboot-Student CRUD
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name="student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String address;
private String course;}
Step4: create StudentRepository.java inside the repository package
//StudentRepository
package com.jojuskills.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.jojuskills.entity.Student;
@Repository
public interface StudentRepository extends CrudRepository<Student, Integer>{ }
Step5: create StudentService.java inside the service package
//Student Service.java
package com.jojuskills.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jojuskills.entity.Student;
import com.jojuskills.repository.StudentRepository;
@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;
//save the student
public void saveOrUpdate(Student s) {
studentRepository.save(s);}
import java.util.List;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.jojuskills.entity.Student;
import com.jojuskills.service.StudentService;
@RestController
public class StudentController {
@Autowired
StudentService studentService;
@PutMapping("/student")
private int saveStudent(@RequestBody Student student) {
studentService.saveOrUpdate(student);
return student.getId();
}
@GetMapping("/student/{id}")
private Student getStudent(@PathVariable("id")int id) {
return studentService.getStudentById(id);
}
@GetMapping("/student_list")
private List<Student> getAllStudents(){
return studentService.getAllStudents();
}
@PutMapping("/stud")
private Student update(@RequestBody Student s) {
studentService.saveOrUpdate(s);
return s;
}
@DeleteMapping("/student/{id}")
private void deleteStudent(@PathVariable("id") int id) {
studentService.delete(id);