본문 바로가기

Back-end/Spring Boot + REST API19

스프링부트 API JPA 최적화 페치조인, 페이징 default_batch_fetch_size 페치조인, 페이징 1. 페이징 엔티티 조회 * 선호하는 방법 중 하나 @GetMapping("/api/v3-1/orders") public ResponseEntity orderV3_page( @RequestParam(value = "offset", defaultValue = "0") String offset, @RequestParam(value = "limit", defaultValue = "100") String limit ) { // N 만큼 데이터 나옴 List orders = repository.findAllWithMemberDelivery(offset, limit); // ToOne 관계이기 때문에 페이징 가능 List result = orders.stream() .map(o -> new Ord.. 2023. 12. 23.
스프링부트 API JPA 최적화 (N+1) 컬렉션 조회 최적화, DTO 조회 성능 향상 컬렉션 조회 최적화 1. 엔티티 조회 - 페치 조인으로 쿼리 수 최적화 OrderApiController /** * 페치 조인 */ @GetMapping("/api/v3/orders") public ResponseEntity orderV3() { // N 만큼 데이터 나옴 List orders = repository.findAllWithItem(); List result = orders.stream() .map(o -> new OrderDto(o)) .toList(); return ResponseEntity.ok(new Result(result)); } Order 엔티티 객체로 쿼리 결과를 받아서 Dto 로 변환작업을 한다음 반환 OrderRepository findAllWithItem() public .. 2023. 12. 21.
스프링부트 API JPA 최적화 ToOne 관계 (N+1 문제) , 페치 조인 ToOne 관계 (N+1 문제) , 페치 조인 지연 로딩과 조회 성능 최적화 주문(Order) 내의 ToOne 관계인 member, delivery 지연로딩 조회 Entity @Table(name = "orders") @Getter @Setter public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_id") private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "member_id") private Member member; // = new ProxyMember()를 생성해서(하이버네이트에서) 넣어둔다. // =.. 2023. 12. 19.
Spring Boot 시큐리티 + JWT 흐름 정리 시큐리티 로그인/회원가입/인증 로그인 @PostMapping("/signup") public ResponseEntity login(@RequestBody MemberDto loginDto) { // add check for email exists in DB if(memberService.existsByEmail(loginDto.getEmail())) { return new ResponseEntity("이메일이 존재합니다.",HttpStatus.BAD_REQUEST); } User user = memberService.memberLogin(loginDto); if(user == null) return new ResponseEntity("회원가입 실패",HttpStatus.INTERNAL_SERVER_ERR.. 2022. 11. 23.
Spring Boot 실행 프로세스와 Embedded Servers , CLI 실행 실행 프로세스 main() 메소드 실행 main() 메소드 내의 SpringApplication.run() 스프링 부트 앱에 대해 부트스트래핑 수행 long startTime = System.nanoTime() to calculate the time taken by Spring boot application 스프링 부트 실행을 위한 환경 준비 (dev, prod, qa, uat) Print banner (콘솔에 스프링 부트 로고 출력) IOC Container 시작 - classpath(default, Web servlet / Reactive)의 ApplicationContext context = createApplicationContext(); return context // Spring IOC con.. 2022. 9. 9.
Spring boot - blog application (REST API) : AWS RDS, Elastic Beanstalk AWS EC2 프로세서, 스토리지, 네트워킹, OS 및 구매 모델의 다양한 옵션을 제공하며, 클라우드에서 안전하고 크기 조정 가능한 컴퓨팅을 제공합니다. Elastic Beanstalk AWS Elastic Beanstalk는 Java, .NET, PHP, Node.js, Python, Ruby, Go 및 Docker를 사용하여 개발된 웹 애플리케이션 및 서비스를 Apache, Nginx, Passenger 및 IIS와 같은 친숙한 서버에서 손쉽게 배포하고 확장할 수 있는 서비스 RDS Amazon Aurora, PostgreSQL, SQL Server 및 MySQL 중에서 선택한 관계형 데이터베이스 S3 확장성, 데이터 가용성, 보안 및 성능을 갖춘 클라우드 객체 스토리지 Route 53 높은 가용성과.. 2022. 9. 8.
Spring boot - blog application (REST API) : Swagger REST API Documentation REST endpoints available Response codes Payload structure Error codes HTTP methods Standard error message Maven io.springfox springfox-swagger-ui 3.0.0 io.springfox springfox-boot-starter 3.0.0 SecurityConfig.java @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .exceptionHandling() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPo.. 2022. 8. 9.
Spring boot - blog application (REST API) : Versioning (버저닝) 버저닝(Versioning) REST APIs 4가지 버저닝 방법을 해볼 것인데요 1. URI Path 2. Query parameters 3. Custom headers 4. Content negotiation 버저닝을 해야되는 상황 request/response format이 바뀌었을 때 (xml, json) property name( name, productName) or 타입이 바뀌었을 때 요구받은 필드를 추가할 때 response에 대한 값을 제거할 때 Versioning through 1. URI Path http://www.example.com/api/v1/empolyees http://www.example.com/api/v2/products ex) Twitter, Pay Pal, Googl.. 2022. 8. 4.
Spring boot - blog application (REST API) : Spring Security + JWT JWT (JSON Web Token) is a tandard that is mostly used for securing REST APIs. JWT follows stateless authentication mechanism. Client and Server 사이에 가장 안전하게 통신하는 방법. Q. 언제 JWT를 사용하면 좋을까? A. Authorization(권한 부여) - 로그인, Information Exchange JWT 구조 토큰값을 디코드하면 , Header, Payload, Signature 정보를 알 수 있다. JWT는 어떻게 동작할까? 1. POST 통신으로 로그인 2. uersname, password의 유효성 검사 이후, Secret Key를 통해 JWT 생성 3. return JWT.. 2022. 8. 2.
Spring boot - blog application (REST API) : Securing REST APIs REST API 에서 스프링 시큐리티는 어떻게 적용이 될까? Dependency org.springframework.boot spring-boot-starter-security application.properties logging.level.org.springframework.security=DEBUG spring.security.user.name=kjh spring.security.user.password=password spring.security.user.roles=ADMIN 실행을 하면 시큐리티 자체 로그인 페이지로 넘어가게 되는데 application.properties 에서 user name, password 를 설정하여 시큐리티에 로그인 할 수 있다. Postman 에서 시큐리티 적용된 서.. 2022. 7. 20.
Spring boot - blog application (REST API) : Validation @Valid 스프링 부트에서 유효성 검사를 해보려고 합니다. Create, Update Post REST API 요청에 대해 유효성 검사 dependency 추가 org.springframework.boot spring-boot-starter-validation 2.7.0 PostDto 에 애노테이션 추가 package com.springboot.blog.payload; @Data public class PostDto { private long id; @NotEmpty @Size(min =2, message="Post title should have at least 2 characters") private String title; @NotEmpty @Size(min= 10, message="Post descripti.. 2022. 7. 6.
Spring boot - blog application (REST API) : Global Exception Handling REST API 에서 a custom error response를 생성하기 Create ErrorDetails Class Create GlobalExceptionHandler Class Test using Postman Client Create ErrorDetails Class package com.springboot.blog.payload; import java.util.Date; import lombok.Getter; @Getter public class ErrorDetails { private Date timestamp; private String message; private String details; public ErrorDetails(Date timestamp, String message, .. 2022. 7. 5.