Spring Boot for Beginners - Part 2

Spring Boot for Beginners - Part 2

No alt text provided for this image

Step 1: Create a Spring Boot Project

  • Go to https://start.spring.io/
  • Make Below choices
  • Select Maven Project and Java, Leave all others in their default options for now
  • Select Dependencies : Spring Web, Spring Data JPA, MySQL Driver and SpringBoot DevTools

No alt text provided for this image

  • Spring Web is to get Spring MVC and Tomcat Server, Spring Data JPA is for Java Persistence Layer and Hibernate, SpringBoot DevTools is simply for Dev tools MySQL Driver is JDBC respectively.
  • Generate project, extract and open downloaded zip from your IDE

Step 2: Connect to Database

No alt text provided for this image

  • Connecting Database to SpringBoot is easy with JPA
  • You just need JDBC connection URL, username and password of your preferred database
  • Make all these changes in application.properties file
  • Set ddl-auto to update (how does it work? )
  • Best Practice is to specify hibernate dialect too.

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;
   
}
;        

  • Models are also known as entities
  • Major components or actors in your application that solves a specific use case
  • @Entity is the annotation used in SpringBoot to mark it as a Entity or model class
  • @id annotations sets the unique primary key of the table which is identified via @table annotation and @GeneratedValue is set to AUTO to enable auto increment
  • generate getters and setters

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> {}

;        

  • This is to enable CRUD (Create, Read, Update, Delete) operations on ResearchTopics
  • To implement Repository @repository annotation is used.
  • If you doubt why repository is a interface not a class. Here you go !
  • and its extended to CrudRepository which is a built-in in SpringBoot

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);
    }
}
;        

  • This is where actual Business Logic is implemented
  • @RestController is the main annotation used
  • @Autowired is to enable dependency injection
  • @GetMapping and @PostMapping are to identify which type of HTTP requests are accepted

Step 6: Compile, Build and Run

  • Run mvn spring-boot:run command in cmd where pom.xml is located
  • or Can do easily from IDE too

Step 7: Test

  • Now the SpringBoot Rest API we developed is running on https://localhost:8080/
  • Let's use Postman or curl to check endpoints
  • Send a GET request to https://localhost:8080/api/researchTopic and you should get a JSON output similar to below

[
   {
  	"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 !





要查看或添加评论,请登录

Nivarthana Sandeepani的更多文章

  • Spring Boot for Beginners - Part 1

    Spring Boot for Beginners - Part 1

    In this article series I wish to take you through a journey from basics of spring boot, how to write a rest API using…

    12 条评论

社区洞察

其他会员也浏览了