Spring 72

35. Entity 연관 관계 기초

테이블 간 관계고객 정보를 가진 users 테이블create table users( id bigint not null auto_increment, name varchar(255), primary key (id));음식 정보를 가진 food 테이블create table food( id bigint not null auto_increment, name varchar(255), price float(53) not null, primary key (id));둘을 이어주는 주문 정보를 가진 orders 테이블create table orders( id bigint not null auto_increment, user_id bigint, ..

34. RestTemplate의 Post 요청, exchange

Post 요청 방법  Client 입장 서버요청 받은 검색어를 Query String 방식으로 Server 입장의 서버로 RestTemplate를 사용하여 요청합니다. public ItemDto postCall(String query) { URI uri = UriComponentsBuilder .fromUriString("http://localhost:7070") .path("/api/server/post-call/{query}") // @PathVariable 방식 .encode() .build() .expand(query) // 위 {} 에 들어갈 값을 넣어준다 .toUri(..

Mock 을 이용한 테스트 코드 - argument matcher

Long seatNum = 1L;// 이건 오류 발생when(lockService.acquireLock(seatNum, anyLong()))    // 이건 정상 작동when(lockService.acquireLock(eq(seatNum), anyLong()))    Mockito의 argument matcher와 일반 인자를 혼용하면 InvalidUseOfMatchersException 발생합니다.모든 인자에 매처를 사용하거나 모든 인자를 일반 값으로 사용해야 합니다. // 모든 인자를 matcher로 처리하는 경우when(lockService.acquireLock(any(), anyLong()))  matcher 사용 규칙:한 메서드 호출에서 matcher 사용 시, 모든 인자에 matcher 적용 ..

AWS S3 버킷 사용하기

MultipartFile 방식1. S3Config   S3 클라이언트를 설정하기 위한 클래스입니다. Amazon S3에 연결하려면 인증 정보와 지역 설정이 필요합니다.accessKey, secretKey, region 정보를 담고 있는  AmazonS3Client를 Bean으로 등록합니다. @Configurationpublic class S3Config { @Value("${cloud.aws.credentials.accessKey}") private String accessKey; @Value("${cloud.aws.credentials.secretKey}") private String secretKey; @Value("${cloud.aws.region.static}") private Stri..

Transaction Propagation

Transaction Propagation은 한 트랜잭션이 동작하고 있을 때, 다른 트랜잭션이 동작하는 경우 어떻게 전파될지를 결정하는 속성입니다. Spring Framework에서 @Transaction 애노테이션을 사용하여 트랜잭션을 선언할 때 설정할 수 있으며, 트랜잭션 경계 설정과 실행 컨텍스트 관리를 유연하게 합니다.   Transaction Propagation의 주요 사용 시점복잡한 비즈니스 로직 분리:하나의 서비스 계층에서 여러 하위 서비스 계층을 호출할 때 각 계층의 트랜잭션 범위를 다르게 설정해야 하는 경우.재사용성 향상:공통 메서드를 다른 서비스에서 재사용하지만, 트랜잭션 전파 방식을 상황에 따라 다르게 적용해야 할 때.롤백 처리 제어:특정 하위 작업은 상위 트랜잭션과 독립적으로 처리..

33. RestTemplate이란 무엇일까?

서비스 개발을 진행하다보면 라이브러리 사용만으로는 구현이 힘든 기능들이 무수히 많이 존재합니다.예를 들어 우리의 서비스에서 회원가입을 진행할 때 사용자의 주소를 받아야 한다면?>> 주소를 검색할 수 있는 기능을 구현해야하는데 직접 구현을 하게되면 많은 시간과 비용이 들어갑니다.이때 카카오에서 만든 주소 검색 API를 사용한다면 해당 기능을 간편하게 구현할 수 있습니다.  우리의 서버는 Client의 입장이 되어 Kakao 서버에 요청을 진행해야합니다.Spring에서는 서버에서 다른 서버로 간편하게 요청할 수 있도록 RestTemplate 기능을 제공하고 있습니다.   Get 요청 방법  - Client 입장의 서버 - RestTemplate을 주입 받습니다.요청 받은 검색어를 Query String 방식..

QueryDsl - Projections 의 4가지 방식

QueryDsl - Projections QueryDsl 을 사용해서 엔티티 전체를 조회하는 것이 아니라 특정 대상만 조회하는 것을 말합니다.  @Entity@Table(name = "team")@Getter@NoArgsConstructorpublic class Team extends Timestamped { @Id private Long id; private String name; private Integer trophyCount;}@Entity@Table(name = "member")@Getter@NoArgsConstructorpublic class Member extends Timestamped { @Id private Long id; private String..

31. Spring Security: JWT 로그인

이전 '24. Spring Security 로그인'에서는 인증이 완료된 클라이언트에게 세션 쿠키를 발급합니다. 이번에는 인증이 완료된 클라이언트에게 JWT를 발급하도록 하겠습니다.   1. JwtAuthenticationFilter : 로그인 진행 및 JWT 생성package com.sparta.springauth.jwt;import com.fasterxml.jackson.databind.ObjectMapper;import com.sparta.springauth.dto.LoginRequestDto;import com.sparta.springauth.entity.UserRoleEnum;import com.sparta.springauth.security.UserDetailsImpl;import jakarta..

30. Spring Security 로그인

Spring Security를 사용한다면 Client 의 요청은 모두 Spring Security 를 거치게 됩니다.Spring Security 역할인증/인가성공 시: Controller 로 Client 요청 전달Client 요청 + 사용자 정보 (UserDetails)실패 시: Controller 로 Client 요청 전달되지 않음Client 에게 Error Response 보냄   Client로그인 시도로그인 시도할 username, password 정보를 HTTP body 로 전달 (POST 요청)로그인 시도 URL 은 WebSecurityConfig 클래스에서 변경 가능아래와 같이 설정 시 "POST /api/user/login" 로 설정됩니다. 인증 관리자 (Authentication Manag..