본문 바로가기
카테고리 없음

JPA(ORM) 스프링부트 CRUD REST API

by 도도대표 2022. 12. 24.
 

다시 처음부터 될때까지 해봐야해 그래야 내것이 되는거야

 

여기서 다양한 예제를 연습해보면 좋음!
일단 처음부터 이렇게 만들 수 있도록 여러번 복습이 더 중요!!

 

 

applicationproperty

server.address=localhost
server.port=8080

spring.jpa.show-sql=true

spring.datasource.url=jdbc:mysql://localhost:3306/smart_farm

spring.datasource.username=root
spring.datasource.password=4579
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.database=mysql

model-user

package com.example.demo.model;

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


@Entity
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;
}


크리에이트를 실행하려면 포스트 메소드를 사용할 수 있는 포스트맨을 활용해야함

 

 

controller-usercontroller

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/get")
    public String getTest() {
        return "success";
    }
위에 있는 샘플은 단순 텍스트만 화면으로 넘겨주는 코드
아래 샘플은 실제제이피에이 활용한 코드라서 위에 샘플은 처음에 테스트 끝나면 버리고 아래 코드를 사용해야함
 @PostMapping("/user")
    public User create(@RequestBody User user) {
        // just insert User object
        // this is very simple more than original
        return userRepository.save(user);
    }
    
    @GetMapping("/user/{id}")
    public String read(@PathVariable Long id) {

        Optional<User> userOptional = userRepository.findById(id);
        userOptional.ifPresent(System.out::println);

        return "successfully executed";
    }

400 bad request 리쿼스트가 잘못됐다는 뜻

username,password,id중에 하나라도 없을때

 

repository-userrepository

package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

댓글