[Spring Boot] JPA 설정 및 사용 방법


 

Java ORM(Object Relational Mapping) 라이브러리인 JPA 설정 및 사용방법에 대해 알아보겠다.


[수행 환경]

Windows 10
IntelliJ 2020.3.4
MariaDB 10.11
java 11
gradle-7.6


[gradle 설정]
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

 

[yml 설정]
spring:
  jpa:
    properties:
         show_sql: true
         format_sql: true

 

[테이블 생성]
CREATE TABLE `agree` (
  `SEQ` int(11) NOT NULL AUTO_INCREMENT COMMENT '시퀀스',
  `MEM_ID` varchar(50) NOT NULL COMMENT '아이디',
  `PHONE` varchar(50) DEFAULT NULL COMMENT '전화번호',
  `EMAIL` varchar(50) DEFAULT NULL COMMENT '이메일',
  `CONTENTS_SEQ` int(11) NOT NULL COMMENT '동의서 컨텐츠 아이디',
  `AGREE_YN` varchar(1) DEFAULT NULL  COMMENT '동의여부',
  `SYS_CREATE_DT` datetime DEFAULT current_timestamp() COMMENT '등록한시간',
  `SYS_CREATE_USR` varchar(50) NULL COMMENT '등록한사람',
  `SYS_UPDATE_DT` datetime DEFAULT current_timestamp() COMMENT '등록한시간',
  `SYS_UPDATE_USR` varchar(50) NULL COMMENT '수정한사람',
  PRIMARY KEY (`SEQ`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;

 

[Entity 클래스 생성]
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.math.BigDecimal;

@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Agree {

  /**
  * 
  */
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long seq;

  /**
  * 
  */
  private String memId;

  /**
  * 
  */
  private long contentsSeq;

  /**
  * 
  */
  private String agreeYn;

  /**
  * 
  */
  private LocalDateTime sysCreateDt;

  /**
  * 
  */
  private String sysCreateUsr;

  /**
  * 
  */
  private LocalDateTime sysUpdateDt;

  /**
  * 
  */
  private String sysUpdateUsr;

}

 

[Repository 클래스 생성]
import org.springframework.data.jpa.repository.JpaRepository;

public interface AgreeRepository extends JpaRepository<Agree, Integer> {

}
[서비스 클래스 생성]
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j                      //로그 기능 추가 Annotation
@Service                    //서비스 컴포넌트로 spring boot에 등록하는 Annotation
@RequiredArgsConstructor    //final로 지정된 맴버변수에 대해서 생성자 자동 생성
public class AgreeService {

    //@RequiredArgsConstructor 선언으로
    //생성자가 자동 생성되면서 컨테이너로 부터 메모리 자동 주입된다.
    final private AgreeRepository agreeRepository;

    /**
     * 임의 데이터 저장
     */
    public void saveAgree() {

        //Agree 데이터 셋팅
        Agree agree = Agree.builder()
                        .agreeYn("Y")
                        .sysCreateDt(LocalDateTime.now())
                        .sysUpdateDt(LocalDateTime.now())
                        .contentsSeq(1)
                        .memId("system")
                        .build();

        //DB에 저장
        agreeRepository.save(agree);
    }
}

 

[Controller 클래스 생성]
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j                      //로그 기능 추가 Annotation
@RequestMapping("/v1")
@RestController             //RestController 컴포넌트로 spring boot에 등록하는 Annotation
@AllArgsConstructor         //final로 지정된 맴버변수에 대해서 생성자 자동 생성
@Api(tags = {"20.동의 API"})
public class AgreeController {

    private final AgreeService agreeService;

    @PostMapping("/agree")
    @ApiOperation(value = "동의 등록")
    public void regAlbum() {
        agreeService.saveAgree();
    }
}

 

[개발한 API 실행]
[DB에 데이터 입력 되었는지 확인]

 

반응형

+ Recent posts