본문 바로가기

H2

JPA CRUD

정보관리의 기본 기능 → 생성 (Create) → 조회 (Read) → 변경 (Update) → 삭제 (Delete) 

JPA로 CRUD 하는 방법을 익혀보기

 

우선 아래와 같이 테이블에 해당하는 도메인,  Course.java 를 만들고

package com.sparta.week01_hwk.domain;

import lombok.NoArgsConstructor;

import javax.persistence.*;

@NoArgsConstructor // 기본생성자를 대신 생성해줍니다.
@Entity // 테이블임을 나타냅니다.
public class Course extends Timestamped {

    @Id // ID 값, Primary Key로 사용하겠다는 뜻입니다.
    @GeneratedValue(strategy = GenerationType.AUTO) // 자동 증가 명령입니다.
    private Long id;

    @Column(nullable = false) // 컬럼 값이고 반드시 값이 존재해야 함을 나타냅니다.
    private String title;

    @Column(nullable = false)
    private String name;

    public Long getId() {
        return this.id;
    }

    public String getTitle() {
        return this.title;
    }

    public String getName() {
        return this.name;
    }

    public Course(String title, String name) {
        this.title = title;
        this.name = name;
    }
}

 

 이처럼 repository에 save(insert) 하고 List<Course> 타입의 리스트인 repository 에서 findAll(select *) 하면 

package com.sparta.week01_hwk;

import com.sparta.week01_hwk.domain.Course;
import com.sparta.week01_hwk.domain.CourseRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import java.util.List;

@EnableJpaAuditing// 생성, 수정에 따른 자동 업데이트 적용
@SpringBootApplication
public class Week02HwkApplication {

    public static void main(String[] args) {
        SpringApplication.run(Week02HwkApplication.class, args);
    }

    // Week02Application.java 의 main 함수 아래에 붙여주세요.
    @Bean
    public CommandLineRunner demo(CourseRepository repository) {
        return (args) -> {// 데이터 저장하기
            repository.save(new Course("프론트엔드의 꽃, 리액트", "임꺽정"));

// 데이터 전부 조회하기
            List<Course> courseList = repository.findAll();
            for (int i = 0; i < courseList.size(); i++) {
                Course course = courseList.get(i);
                System.out.println(course.getId());
                System.out.println(course.getTitle());
                System.out.println(course.getName());
            }

// 데이터 하나 조회하기
            Course course = repository.findById(1L).orElseThrow(
                    () -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")//논리적으로 맞지 않을때 예외처리
                    // 지금처럼 null 값이 들어오는 예외는 NullPointException도 사용 가능
            );
        };
    }
}

id 가 1 인 row의 데이터가 콘솔에 출력된다. 예를 들어 존재하지 않는 2L를 조회하면

아까 작성한 예외 처리가 콘솔에 출력된다.

이번엔 업데이트를 해보자

우선 Course.java에 update메서드 추가

 

패키지 생성

week02 > service 

> CourseService.java 생성

package com.sparta.week02_hwk.service;

import com.sparta.week02_hwk.domain.Course;
import com.sparta.week02_hwk.domain.CourseRepository;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service // 스프링에게 이 클래스는 서비스임을 명시
public class CourseService {

    // final: 서비스에게 꼭 필요한 녀석임을 명시, 변형 불가.
    private final CourseRepository courseRepository;

    // 생성자를 통해, Service 클래스를 만들 때 꼭 Repository를 넣어주도록
    // 스프링에게 알려줌
    public CourseService(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    @Transactional // SQL 쿼리가 일어나야 함을 스프링에게 알려줌
    public Long update(Long id, Course course) {
        Course course1 = courseRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")
        );
        course1.update(course);
        return course1.getId();
    }
}

메인함수 재작성//저장, 조회, 업데이트 실행하기

@Bean
public CommandLineRunner demo(CourseRepository courseRepository, CourseService courseService) {
    return (args) -> {
        courseRepository.save(new Course("자바스크립트의 꽃, React", "홍유찬"));//저장

        System.out.println("데이터 인쇄");
        List<Course> courseList = courseRepository.findAll();//조회
        for (int i=0; i<courseList.size(); i++) {
            Course course = courseList.get(i);
            System.out.println(course.getId());
            System.out.println(course.getTitle());
            System.out.println(course.getName());
        }

        Course new_course = new Course("자바의 봄, Spring", "홍유찬");
        courseService.update(1L, new_course);//업데이트
        courseList = courseRepository.findAll();
        for (int i=0; i<courseList.size(); i++) {
            Course course = courseList.get(i);
            System.out.println(course.getId());
            System.out.println(course.getTitle());
            System.out.println(course.getName());
        }
    };
}

실행 하면 요렇게~ 출력

마지막으로 삭제는 한줄만 추가해주면 된다.

하단에 데이터를 조회하고 예외처리를 해주면 널값으로 예외 코드를 확인 할 수있다..

'H2' 카테고리의 다른 글

JPA로 생성일자, 수정일자 필드 만들기  (0) 2020.11.15
JPA 사용해보기  (0) 2020.11.15
JPA 시작하기  (0) 2020.11.15
H2 웹콘솔 띄우기  (0) 2020.11.14