Spring

Spring Data JPA 세팅하기

YooKyungHun 2023. 3. 23. 12:58

127.0.0.1 connection 연결하기

로컬 connection 을 추가하면 자동으로 만들어진 sys 스키마의 sys_config 테이블 확인가능

 

 

Spring Data JPA

프로젝트 생성 후 

 

Spring Boot 프로젝트 생성하기

Spring Initializr https://start.spring.io [Spring Boot] spring initializr 사용하기 spring initializr spring boot 기반으로 spring 관련 프로젝트를 생성해주는 사이트로 project를 다운로드 하여 쉽게 사용 가능하다. https://

ygeum2.tistory.com

 

build.gradle 에서 의존성 추가

dependencies {
	// MySQL
	implementation 'mysql:mysql-connector-java:8.0.32'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
}

 

application.properties 에서 아래 설정 추가

# MySQL 설정
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# DB Source URL
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/sys?serverTimezone=UTC&characterEncoding=UTF-8

# DB username
spring.datasource.username=root

# DB password
spring.datasource.password={비밀번호}

# true 설정 시 실행되는 쿼리문 로그로 확인 가능
spring.jpa.show-sql=true

# DDL(create, alter, drop) 자동 실행 기능
spring.jpa.hibernate.ddl-auto=update

# JPA의 구현체인 Hibernate가 동작하면서 발생한 SQL의 가독성을 높여준다.
spring.jpa.properties.hibernate.format_sql=true

# JPA 데이터베이스 플랫폼 지정 (현재 MYSQL InnoDB를 사용중)
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

 

Entity 추가하기

src > main > java > com > jscode > day05 > entity > TestTable Class 작성

package com.jscode.day05.entity;

import javax.persistence.*;

@Table(name = "tb_test")
@Entity
public class TestTable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;

    public TestTable() {
    }
}
  • @Table
    • 맵핑할 테이블을 지정
  • @Entity
    • 접근 제어자가 public 혹은 protected 인 기본 생성자가 필수입니다.
    • final 클래스, enum, interface, inner 클래스에는 사용이 불가능합니다.
    • 저장하려는 속성은 final 이면 안됩니다.
  • @Id
    • 해당 테이블의 PK 필드
  • @GeneratedValue
    • PK의 생성 규칙 표시
    • Spring Boot 2.0부터는 auto_increment 를 위해서 GenerationType.IDENTITY 옵션 추가 필수
  • @Column
    • 테이블의 칼럼임을 표시
    • 필수 x, 기본값 외에 변경이 필요한 옵션이 존재할 경우 사용