Spring Boot for Beginners - Part 2
Nivarthana Sandeepani
Technopreneur| Mentor | Fullstack Developer |React | Node.js | Java | Kotlin | AWS | I help organizations for Business Growth with Innovative Technology Solutions
Step 1: Create a Spring Boot Project
Step 2: Connect to Database
Step 3 : Create Model
package com.example.demo.model
import javax.persistence.*;
@Entity
@Table(name = "researchTopics")
public class ResearchTopic {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String reference;
}
;
Step 4 : Repository Class
package com.example.demo.repository
import com.example.demo.model.ResearchTopic;
import org.springframework.data.repository.CrudRepository;
public interface ResearchTopicsRepository extends CrudRepository<ResearchTopic, Long> {}
;
Step 5 : Create a Controller
package com.example.demo.controller
import com.example.demo.model.ResearchTopic;
import com.example.demo.repository.ResearchTopicsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/researchTopic")
public class researchTopicController {
@Autowired
private ResearchTopicsRepository researchTopicsRepository;
领英推荐
To Get Research Topic
@GetMapping
public List<ResearchTopic> findAllTopic() {
return (List<ResearchTopic>) researchTopicsRepository.findAll();
To Get Research Topic By ID
@GetMapping("/{id}")
public ResponseEntity<ResearchTopic> findTopicById(@PathVariable(value = "id") long id) {
Optional<ResearchTopic> researchTopic = researchTopicsRepository.findById(id);
if(researchTopic.isPresent()) {
return ResponseEntity.ok().body(researchTopic.get());
} else {
return ResponseEntity.notFound().build();
To Create a Topic
@PostMapping
public ResearchTopic saveTopic(@Validated @RequestBody ResearchTopic researchTopic) {
return researchTopicsRepository.save(researchTopic);
}
}
;
Step 6: Compile, Build and Run
Step 7: Test
[
{
"id": 1,
"name":"Bioinformatics and Computational Biology",
"reference":"https://cse.umn.edu/cs/bioinformatics
field_category_target_id=7071"
}
]
Other HTTP methods should give responses with 200 OK. Try out some new things with the theories learnt. Hope you got an idea on developing a REST API with spring boot. We will discuss how to implement more complex backend with spring boot in next article.
Let's Clear out all your doubts in Spring Boot so far before that. See you !