DB에 데이터 생성하기

Gyuhan Park·2022년 7월 24일
0

spring

목록 보기
7/18

JPA를 활용한 DB에 데이터 생성

server : java / database : SQL
server와 DB가 서로 소통할 수 있도록 JPA가 연결.

근데 JPA가 뭐야?

JPA(Java Persistence API)
Java에서 ORM 표준으로 사용하고 있는 인터페이스 모음
java aplication에서 RDB 사용 방식을 정의한 인터페이스 모음

JPA를 왜 쓸까?

객체 중심으로 개발 가능
반복적인 CRUD SQL 처리
생산성, 유지보수 good

ORM은 뭔데?

ORM(Object-Relational Mapping)
자바 클래스와 RDB의 테이블을 연결하는 것
객체 간의 관계를 바탕으로 SQL 자동 생성
SQL문 필요없이 객체를 통해 간접적으로 DB 조작

JPA 핵심 기능

  1. Entity : DTO를 DB가 이해할 수 있는 데이터로 규격화.
  2. Repository : 일꾼. Entity를 DB에 저장하는 기능 포함.

[DB 데이터 생성 과정]
1. 폼 데이터가 담긴 DTO를 DB가 이해할 수 있는 Entity로 변환.
2. 변환된 Entity를 Repository가 DB에 저장.

# entity

src > main > java > 기본 package > entity package
@Id : DB는 각각의 데이터를 구분할 고유의 데이터가 필요.
@GeneratedValue : 값을 넣지 않아도 자동으로 숫자 대입.
@Column : 필드값을 DB의 column으로 인식.

package com.example.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Article {

    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String title;

    @Column
    private String content;

    public Article(Long id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

# controller

@Autowired : spring boot가 미리 만들어놓은 객체를 가져다가 자동 연결. new 명령어로 새로운 객체를 생성하지 않아도 됨.

package com.example.demo.controller;

import com.example.demo.dto.ArticleForm;
import com.example.demo.entity.Article;
import com.example.demo.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class articleController {

    @Autowired
    ArticleRepository articleRepository;

    @GetMapping("/article")
    public String viewForm(){
        return "articles/new";
    }

    @PostMapping("/article/create")
    public String getFormData(ArticleForm form){
        System.out.println(form.toString());

//        1. DTO -> Entity
        Article article = form.toEntity();
        System.out.println(article.toString());

//        2. Repository가 Entity를 DB에 넣게 하기
        Article saved = articleRepository.save(article);
        System.out.println(saved.toString());

        return "";
    }
}

# repository

src > main > java > 기본 package > repository package > interface 생성
CrudRepository를 상속받아 사용.
<관리할 Entity, id값의 타입> 을 인자로 받음.

package com.example.demo.repository;

import com.example.demo.entity.Article;
import org.springframework.data.repository.CrudRepository;

public interface ArticleRepository extends CrudRepository<Article, Long> {
}

h2 database 에서 데이터 조회하기

src > main > resources > aplication.properties
spring.h2.console.enabled = True

localhost:8080/h2-console 접속
서버 실행 시 나오는 h2 memory 주소를 검색해서 넣기

profile
단단한 프론트엔드 개발자가 되고 싶은

0개의 댓글