IT/etc

[Spring Boot] MySQL & JPA 연동 (gradle프로젝트)

음료요정 2022. 3. 23. 16:08

1. 프로젝트에 의존성 추가하기

    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'mysql:mysql-connector-java'

 

 

2. DB에 MySQL과 JPA 관련 설정 정보 추가하기

#Mysql 연결
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/new_schema?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=1234

#JPA 관련정보
## JPA 쿼리문 확인 가능
spring.jpa.show-sql=true
## DDL 정의, DB 고유기능을 사용 가능
spring.jpa.hibernate.ddl-auto=update
## JPA 구현체 Hibernate가 동작하며 발생한 SQL 가독성을 높여준다
spring.jpa.properties.hibernate.format_sql=true

 

3. JPA의 객체로 사용할 Entity 클래스를 생성

@Table(name="tb_product")
@Entity
public class ProductEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // MySQL의 AUTO_INCREMENT를 사용
    private Long productId;
    private String title;
    private Integer totalInvestingAmount;
    private ProductStatus status;
    private LocalDateTime startedAt;
    private LocalDateTime finishedAt;
}

 

4. JPA Repository 생성

Spring Data JPA는 JPA의 구현체인 Hibernate를 이용하기 위한 여러 API를 제공합니다.

그 중에서 가장 많이 사용되는 것이 바로 JPA Repository라는 인터페이스이다.

JpaRepository 를 상속받아 만들면 작업 끝