본문 바로가기

Portfolio 제작기

Spring boot 의 Controller, Model, Repository 작성(간단한 예시)

Spring boot 공식문서를 기반으로 작성되었음 https://spring.io/guides/gs/accessing-data-mysql

 

User 모델 코드는 아래와 같다.

User.java

package com.example.accessing_data_mysql;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

 

@Entity Annotation을 사용하고 필드를 선언한 뒤 각 필드에 대한 getter와 setter를 정의해준다.

User 모델에는 id, name, email 필드가 있다. 각 필드에 대한 getter와 setter를 타입에 맞게 정의해준다.

 

 

아래는 UserRepository 코드의 예시이다.

package com.example.accessing_data_mysql;

import org.springframework.data.repository.CrudRepository;

import com.example.accessing_data_mysql.User;

public interface UserRepository extends CrudRepository<User, Integer> {

}

 

아직은 잘 모르지만 컨트롤러에서 @Autowired Annotation을 사용하여 UserRepository를 userRepository로 받고 DB를 조작하거나 조건에 맞는 row를 조회할 때 repository를 이용해서 할 수 있는 것 같다.

 

다음은 컨트롤러 코드 예시다

MainController.java

package com.example.accessing_data_mysql;

import com.example.accessing_data_mysql.User;
import com.example.accessing_data_mysql.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(path="/demo")
public class MainController {
    @Autowired
    private UserRepository userRepository;

    @PostMapping(path="/add")
    public @ResponseBody String addNewUser (
            @RequestParam String name,
            @RequestParam String email
    ) {
        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        return userRepository.findAll();
    }
}

 

@Controller라는 Annotation을 기입해주며 매핑되는 path 시작점을 결정해주기도 했다.

@RequestMapping(path="/demo") 가 그 부분이다.

 

/demo 뒤로 라우팅 되도록 하는 path를 결정할 수 있다.

POST /demo/add 요청에 대해서는 파라미터로 받은 값들을 통해 User Entity를 생성하여 userRepository를 통해 DB에 저장한다.

 

즉 여기서 알 수 있는 것은

라우팅 경로를 고정적으로 결정하는 것을 Controller의 path를 조정하여 결정한다.

각 요청에 대해서 경로를 지정하는 것은 메서드 위에 @{Type}Mapping(path={location})으로 조정하여 결정한다.

 

흐름 그림

 

레파지토리가 DB 접근을 매개해준다.

 

 

위 사진은 요청의 예시이다.