Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
Today
Total
관리 메뉴

요리사에서 IT개발자로

스파르타 부트캠프 스프링 부트 프로젝트 생성 및 CR (다락방) 본문

Spring

스파르타 부트캠프 스프링 부트 프로젝트 생성 및 CR (다락방)

H.S-Backend 2024. 6. 12. 19:53

build.gradle 

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'com.mysql:mysql-connector-j'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

validation -> 사용자 관점에서 시스템 검증 활동을 의미한다.

 

@Valid

Controller안의 로직 중 인풋값@Valid를 설정하면

제공된 라이브러리  로직 중 해당 로직이 검증을 하고 수행한다.

검증을 더 자세히 해준다.

https://tech-sherpa.tistory.com/12

 

개발 과정에서 만난 용어: verification vs validation

전공 공부하는 과정에서 verification과 validataion이라는 단어를 많이 볼 수 있습니다. 영한사전으로 검색하면 둘 다 '확인'이라는 뜻으로 검색됩니다. 그래서 검색을 해보니, 저 이외에도 많은 분들

tech-sherpa.tistory.com

 

Jpa(Java Persistence API) 

 

자바진영에서

ORM(Object-Relational Mapping) 기술 표준으로 사용되는 인터페이스 모음

https://dbjh.tistory.com/77

 

[Spring JPA] JPA 란?

이번 글에서는 JPA(Java Persistence API)가 무엇인지 알아보려고한다. JPA는 자바 진영에서 ORM(Object-Relational Mapping) 기술 표준으로 사용되는 인터페이스의 모음이다. 그 말은 즉, 실제적으로 구현된것이

dbjh.tistory.com

 

Web

웹으로 API를 호출하기 위해 사용되는 Http Client 모듈

https://happycloud-lee.tistory.com/220

 

Spring WebClient 쉽게 이해하기

1. Spring WebClient 이해 이 글을 읽기 전에 먼저 일하는 방식 변화를 이끌고 있는 애자일, 마이크로서비스, 데브옵스, 클라우드에 대해 기본적인 이해를 하실것을 권장 합니다. https://happycloud-lee.tisto

happycloud-lee.tistory.com

 

Lombok

기계적인 코드작성을 자동화 하여

코드 다이어트를 해주는 Java 필수 라이브러리

@Getter @Setter 등등

 

https://mangkyu.tistory.com/78

 

[Java] Lombok이란? 및 Lombok 활용법

Java 언어를 이용해 개발을 하다 보면 기계적으로 작성해야 하는 코드들이 상당히 많다. 이번에는 기계적인 코드 작성을 자동화하여 코드 다이어트를 해주는 Java 필수 라이브러리 Lombok에 대해 알

mangkyu.tistory.com


application.properties 

spring.application.name=SettingProject

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_services
spring.datasource.username=이름
spring.datasource.password=비밀번호

spring.jpa.database=mysql
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

MySQL의 데이터 베이스 연동을 하기위해

name, url, username, password 는 기본으로 설정

 

spring.jpa.database

사용하는 데이터 베이스 종류를 입력

 

spring.jpa.hibernate.ddl-auto

none:

기본값, 데이터베이스 구조 변경x

update 

Hibernate 주어진 엔티티 구조에 따라 데이터베이스를 변경

create 

데이터베이스를 생성은 하되 닫을 때 삭제하지 않는다.

create-drop 

데이터베이스를 생성하고 SessionFactory가 닫힐 때 삭제. 생성하고 서버닫으면 삭제

 

spring.jpa.generate-ddl 

  • 시작시 스키마를 초기화할 지 여부

 

spring.jpa.database-platform

  • MySQL은 org.hibernate.dialect.MySQL8Dialect
  • PostgreSQL은 org.hibernate.dialect.PostgreSQLDialect 

 

spring.jpa.properties.hibernate.format_aql:

  • log가 console에 SQL문을 출력한다.

spring.jpa.hibernate.jdbc.time_zone

  • @createdAt,@updatedAt 타임 스탬프 시간을 설정한다.
spring.jpa.properties.hibernate.jdbc.time_zone=UTC

https://chung-develop.tistory.com/143

 

[해결]JPA 사용 시 DB 에 들어가는 시간과 실제 시간이 안맞는 경우

[해결]JPA 사용 시 DB 에 들어가는 시간과 실제 시간이 안맞는 경우 가끔 JPA 를 사용하다 보면 @createdAt 이나 @updatedAt 과 같이 자동으로 타임스탬프를 찍어주는 기능을 사용하는데 이 때 찍혀들어가

chung-develop.tistory.com

 

 

 

https://pcm9881.tistory.com/130

 

[Spring] MySQL 연동 (JPA, application.properties)

# Spring DataSource (MySQL) spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/데이터베이스명?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username=아이디 sp

pcm9881.tistory.com

 

 


Create 

생성하려면 Entity가 필요하고

public class Card {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String number;

Client에게 요청 로직 (Request)받을 Dto를 생성하고

public class CardReqeustDto {
    private String number;
}

Controller에서 Url에 접근 하게 해주고 

@PostMapping("/cards")
public ResponseEntity<Card> createCard(@RequestBody CardReqeustDto cardRequestDto) {
    Card createdCard = cardService.createCard(cardRequestDto);
    return ResponseEntity.status(HttpStatus.CREATED).body(createdCard);
}

 caredService의 createCard로 접근하여

Service에서 로직을 구현해주고

public Card createCard(CardReqeustDto cardRequestDto) {
    String number = cardRequestDto.getNumber();
    Card card = new Card(number);
    return cardRepository.save(card);
}

caredRequestDto의 요청을 저장할 number를

Card card = new Card(number) 저장할 수 있는 

Card Entity에서 생성자를 선언

public Card(String number) {
    this.number = number;
}

이제 cardRepository에 save 메소드를 사용하여 card를 저장

public interface CardRepository extends JpaRepository<Card, Long> {
}

return 

return ResponseEntity.status(HttpStatus.CREATED).body(createdCard);

 


Read

@PathVariable 

url에 id를 입력하면

controller를 타고

@GetMapping("/cards/{id}")
public ResponseEntity<CardResponseDto> getCardById(@PathVariable Long id) {
    CardResponseDto cardResponseDto = cardService.getCardById(id);
    return ResponseEntity.ok().body(cardResponseDto);
}

 

getCardByID에 id는

cardRepository의 findById(id) 를 넣고

.map을 사용하여 CardResponseDto를 생성 및 선언에 입력값을 넣고 저장 후 

optionalCard에 다시 입력

그렇게 보내지고 

public CardResponseDto getCardById(Long id) {
    Optional<Card> optionalCard = cardRepository.findById(id);
    return optionalCard.map(CardResponseDto::new).orElse(null);
}

 

return 하게된다.

return ResponseEntity.ok().body(cardResponseDto);

 

 

 

중요

 ResponseEntity<List<CardResponseDto>>

로 클래스를 설정하면

 

List<CardResponseDto> cardResponseDtos

ReponseEntity는 

 

return ResponseEntity.ok().body(cardResponseDtos);

이렇게 List<CardResponseDto> 형식만 가능하다. 

 

 

 

반응형