BACK 

Springboot Application

Springboot Application 1. Create the database. 2. Creating application. 3. Creating an entity class. 4. Create REST Controller class with cross origin. 5. Create service interface which has abstract methods. 6. Create an implementation class which implements the service interface. 7. Create an JPA Repository Database Name: vcube DDL: CREATE TABLE `students` ( `id` bigint NOT NULL AUTO_INCREMENT, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci Creating a Springboot Project and Imporing http://start.spring.io - create a Spring Boot project. Note: Verify the Package structure and POM.XML Open Eclipse and click on Import for importing the downloaded spring io project structure Select the maven – existing maven projects Importing the project and Building the structure: Create the database in MySQL (Ex: Workbench) Create database vcube; Set the application.properties file: spring.datasource.url = jdbc:mysql://localhost:3307/vcube spring.datasource.password=root spring.datasource.username=root # Hibernate ddl auto (create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect ## MySQL password installation password needs to be given here…. DemoApplication.java package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Create the Model Layer – Entity Class - Student Package and Import statements package com.example.demo.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; Student class data – create in package: package com.example.demo.model; id - primary key firstName - First name lastname – Last Name student class @Entity @Table(name = "students") public class Student { } Data/ Attributes of the Student Entity Class private long id; private String firstName; private String lastName; private String password; default and parameterized constructors of student class public Student() { } public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } Student class getters and setters @Id @GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY ) public long getId() { return id; } public void setId(long id) { this.id = id; } Column firstname, lastname its getters and setters @Column(name = "first_name", nullable = false) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "last_name", nullable = false) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override method @Override public String toString() { //Coverted object as a string - override the toString() of the Object class return "Student [id=" + id + ", firstName=" + firstName +" + ", lastName=" + lastName +"]"; } Create controller class in the package: package com.example.demo.controller import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; Note: If error at validation.Vaid statement, then write the dependency in POM.XML <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.0.Final</version> </dependency> Cross-Origin Resource Sharing (CORS) @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api/v1") Note : In case of "Javax Persistence unable to compile on maven" error Add the following dependency in POM.XML file <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>2.1.0</version> <scope>compile</scope> </dependency> Note : In case of "JDK 17 and above" or "Spring 6+" you would now need to replace javax.persistence.Entity when with jakarta.persistence.Entity to resolve the jpa entity is not a managed type error Oracle has decided to transfer the ownership, transition to the creation and usage of Jakarta EE. In this process, naming conventions has been changed. The "Javax" namespace (Java EE) was replaced with the "Jakarta" namespace in Jakarta EE. Java and Spring Boot new versions have adopted Jakarta EE from JDK17 and Spring Boot v3. So, you needed to use to jakarta.persistence.Entity. This change impacts and usage shifted from Java EE to Jakarta EE and the package naming conventions has been updated. The following is the imported packages for Entity Class import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; Student Controller class - @Autowired with Student Service public class StudentController { @Autowired private StudentServiceImpl studentService; } Student Controller Import section import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; 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.example.demo.model.Student; import com.example.demo.repository.StudentRepository; import com.example.demo.service.StudentService; import com.example.demo.service.StudentServiceImpl; import com.example.exception.ResourceNotFoundException; In Student Controller Class - POSTMAPPING request @PostMapping("/students") public Student createStudent(@Valid @RequestBody Student student) { //displaying student object in console for confirmation System.out.println(student); return studentService.createStudent(student); } Student Service Interface imports import java.util.List; import java.util.Optional; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.example.demo.model.Student; Student Service Interface Method public interface StudentService { public Student createStudent(Student student); } Service Implementation Class which implements Service Interface – Import methods import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.example.demo.model.Student; import com.example.demo.repository.StudentRepository; Service Implementation Class @Service public class StudentServiceImpl implements StudentService { Autowire Repository object in Service Implementation class @Autowired private StudentRepository studentRepository; ServiceImpl class create student method @Override public Student createStudent(Student student) { return studentRepository.save(student); } Repository interface which extends JpaRepository for CRUD Operations import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.example.demo.model.Student; @Repository public interface StudentRepository extends JpaRepository<Student, Long> { } GetMapping for getting all students in controller @GetMapping("/students") public List getAllStudents() { //storing return type of Student Entity return studentService.getAll(); } Student Service Interface method – getting all data public List getAll(); ServiceImple method for getting all students data public List getAll() { return studentRepository.findAll(); } Create ResourceNotFoundException class in com.example.exception packge package com.example.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends Exception{ private static final long serialVersionUID = 1L; public ResourceNotFoundException(String message){ super(message); } } GetMapping by student ID in Controller @GetMapping("/students/{id}") public ResponseEntity getStudentById(@PathVariable(value = "id") Long studentId) throws ResourceNotFoundException { Student student = studentService.findByStudentId(studentId) .orElseThrow(() -> new ResourceNotFoundException("student not found for this id :: " + studentId)); return ResponseEntity.ok().body(student); } Student Service Interface method – get student by ID public Optional<Student> findByStudentId(long studentId); Student Service Implementation method – get student by ID public Optional<Student> findByStudentId(long studentId){ return studentRepository.findById(studentId); } Put Mapping by student ID - Student Controller @PutMapping("/students/{id}") public ResponseEntity updateStudent(@PathVariable(value = "id") Long studentId, @Valid @RequestBody Student studentDetails) throws ResourceNotFoundException { Student student = studentService.findByStudentId(studentId) .orElseThrow(() -> new ResourceNotFoundException("Student not found for this id :: " + studentId)); student.setFirstName(studentDetails.getFirstName()); final Student updatedStudent = studentService.save(student); return ResponseEntity.ok(updatedStudent); } Student Service Interface – Student Update method public Student save(Student student); Student ServiceImpl method – student Update public Student save(Student student) { // TODO Auto-generated method stub return studentRepository.save(student); } Delete student – student controller @DeleteMapping("/students/{id}") public Map deleteStudent(@PathVariable(value = "id") Long studentId) throws ResourceNotFoundException { Student student = studentService.findByStudentId(studentId) .orElseThrow(() -> new ResourceNotFoundException("Student not found for this id :: " + studentId)); studentService.delete(student); Map response = new HashMap<>(); response.put("deleted", Boolean.TRUE); return response; } Student Service Interface method – delete student public void delete(Student student); Student ServiceImpl method – delete student public void delete(Student student){ studentRepository.delete(student); } Maven – POM.XML <?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.7.12</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.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>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.0.Final</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> BACK