In this tutorial we will demo a Spring Boot CRUD application using REST + Spring Boot JPA + H2 + Gradle.
Create a spring boot project with below dependencies:
build.gradle:
dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' runtimeOnly 'com.h2database:h2' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' }
application.properties:
spring.h2.console.enabled=true spring.datasource.url=jdbc:h2:mem:testdb spring.data.jpa.repositories.bootstrap-mode=default
Model class:
@Data @NoArgsConstructor @AllArgsConstructor @Entity public class Person { @Id @GeneratedValue private int id; private String name; private Integer age; }
Repository:
@Repository public interface MyRepository extends CrudRepository<Person,String>{ }
Service class:
@Service public class MyService { @Autowired MyRepository myRepository; public Iterable<Person> getPersons() { return myRepository.findAll(); } public Person addPerson(Person person) { return myRepository.save(person); } public Person updatePerson(Person person, String id) { Person person2 = myRepository.findById(id).get(); person2.setName(person.getName()); person2.setAge(person.getAge()); return myRepository.save(person2); } public Person getPersonById(String id) { Person person = myRepository.findById(id).get(); return person; } public void deletePerson(String id) { myRepository.deleteById(id); } }
Controller class:
@RestController @CrossOrigin(origins="http://localhost:4200/") @RequestMapping("/api") public class MyController { @Autowired MyService myService; @GetMapping("/getPersons") public Iterable<Person> getPersons() { return myService.getPersons(); } @PostMapping("/addPerson") //@ResponseStatus(HttpStatus.CREATED) public Person addPerson(@RequestBody Person person){ return myService.addPerson(person); } @PutMapping("/updatePerson/{id}") public Person updatePerson(@RequestBody Person person, @PathVariable String id){ return myService.updatePerson(person,id); } @GetMapping("getPersonById/{id}") public Person getPersonById(@PathVariable String id){ return myService.getPersonById(id); } @DeleteMapping("/deletePerson/{id}") public void deletePerson(@PathVariable String id) { myService.deletePerson(id); } }
Now start the application.
Do a POST call to below url with the below request:
http://localhost:8080/api/addPerson
{ "name": "Prasanna Kumar", "age": 46 }
Here is the screenshot for the same:
To see the DB console: http://localhost:8080/h2-console
Hit “Connect” without any password.
You will land up in the console. There you can see all the tables:
Similarly you can test other API endpoints for – GET, PUT and DELETE operations.
Source code of the above example is here: https://github.com/heapsteep/ReST
If you want to know how to create a Spring Boot ReST with MongoDB click here.