Woopii Vyeolog

[spring boot] JPA sample 본문

Spring Boot

[spring boot] JPA sample

WooPii 2022. 2. 4. 02:32

● maven dependency 추가

1. pom.xml에 다음과 같이 추가

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

 

● Entity, repository, service, controller 추가

1. Entity 추가

package com.project.clone_louisquatorze.sample.jpa.entity;

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

@Entity         //jpa의 Entity임을 선언 
@Table(name = "tb_sample")  //테이블 명을 명시
public class SampleEntity {

    @Id        //기본 키 지정
    @GeneratedValue(strategy = GenerationType.IDENTITY) //값 자동 생성 (IDENTIFY : 기본 키 생성을 데이터베이스에 위임)
    private Long id;

    @Column(length = 255, nullable = false)     //column 지정, 길이 : 255, null을 허용하지 않음
    private String name;


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

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

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

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


    @Override
    public String toString() {
        return "{" +
            " id='" + getId() + "'" +
            ", name='" + getName() + "'" +
            "}";
    }
}

 

2. repository 추가

package com.project.clone_louisquatorze.sample.jpa.repository;

import com.project.clone_louisquatorze.sample.jpa.entity.SampleEntity;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository     //Repository임을 선언
public interface SampleRepository extends JpaRepository<SampleEntity /*대상 Entity 입력*/, Long /*대상 Entity의 pk type을 입력*/> {
    
}

 

3. service, service implement 추가

##service

package com.project.clone_louisquatorze.sample.jpa.service;

import java.util.List;
import com.project.clone_louisquatorze.sample.jpa.entity.SampleEntity;

public interface SampleService {
    
    //Sample Entity의 전체 데이터 조회
    public List<SampleEntity> list();

}

 

##serviceImpl

package com.project.clone_louisquatorze.sample.jpa.service.implement;

import java.util.List;

import com.project.clone_louisquatorze.sample.jpa.entity.SampleEntity;
import com.project.clone_louisquatorze.sample.jpa.repository.SampleRepository;
import com.project.clone_louisquatorze.sample.jpa.service.SampleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SampleServiceImpl implements SampleService{

    //Repository 의존성 추가
    @Autowired
    private SampleRepository sampleRepository;

    /**
     * 데이터 전체 조회
     */
    //interface에 정의한 메소드를 override
    @Override
    public List<SampleEntity> list() {

        List<SampleEntity> list = sampleRepository.findAll();

        return list;
    }
    
}

 

 

4. Controller 추가

package com.project.clone_louisquatorze.sample.jpa.controller;

import java.util.List;

import com.project.clone_louisquatorze.sample.jpa.entity.SampleEntity;
import com.project.clone_louisquatorze.sample.jpa.service.SampleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller //Controller 임을 명시
@RequestMapping(value = "/api/sample")  //url prefix 명시
public class SampleController {

    //service를 의존성 추가
    @Autowired
    private SampleService sampleService;


    /**
     * 전체 데이터 조회
     * @return 전체 데이터
     */
    @GetMapping(value = "/list")
    public ResponseEntity<?> list() {

        List<SampleEntity> list = sampleService.list();

        return ResponseEntity.ok().body(list);
    }
    
}

 

 

● application.yml 파일에 설정 추가

## 스프링 버전 2.5 이후 부터 SQL Script DataSource Initialization 기능이 변경 되면서, data.sql 스크립트는 hibernate가 초기화되기 전에 실행되며 hibernate에 의해 생성된 스키마에 데이터를 넣기 위해 data.sql을 사용하고 싶으면 spring.jpa.defer-datasource-initialization 이 값을 true로 하라고 되어있다.

Hibernate and data.sql
By default, data.sql scripts are now run before Hibernate is initialized. This aligns the behavior of basic script-based initialization with that of Flyway and Liquibase. If you want to use data.sql to populate a schema created by Hibernate, set spring.jpa.defer-datasource-initialization to true. While mixing database initialization technologies is not recommended, this will also allow you to use a schema.sql script to build upon a Hibernate-created schema before it’s populated via data.sql.

 

따라서, 다음과 같이 설정 파일을 입력한다.

spring:
    h2:
        console:
            enabled: true
            path: /h2-console

    datasource:
        driverClassName: org.h2.Driver
        #url: jdbc:h2:file:./target/h2db/db/application;DB_CLOSE_DELAY=-1
        url: jdbc:h2:mem:testdb
        username: sa
        password:
        # DB초기화(schema.sql, data.sql) , [always : 기동 시 매번 동작, never : 기동 시 동작하지 않음]
        schema: classpath*:initdata/${database}/schema.sql
        data: classpath*:initdata/${database}/data.sql
        #schema: classpath*:initdata/h2db/schema.sql
        #data: classpath*:initdata/h2db/data.sql
        initialization-mode: always

    jpa:
        defer-datasource-initialization: true   #jpa 사용 환경에서 data.sql을 정상적으로 동작하게 하는 옵션

 

 

 

● 동작 확인

1. 데이터베이스 구조

 

 

2. 브라우저에서 url로 호출

Comments