본문 바로가기

spring

(14)
[JPA] failed to lazily initialize a collection 0. 에러 상황 TestCode 작성 중 단순 save - find 코드를 작성했는데 아래와 같은 에러가 발생 failed to lazily initialize a collection of role: com.demo.jpastudy.entity.UserEntity.addressList, could not initialize proxy - no Session org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.demo.jpastudy.entity.UserEntity.addressList, could not initialize proxy - no Session at app//org.hib..
[JPA] Null value was assigned to a property exception 1. 에러 원인 JPA를 사용해 개발을 하다 보면 database column은 nullabel 속성이지만 entity의 field는 primitive 타입으로 설정할 때가 있다. 그럴 때 primitive type에는 null 값을 할당할 수 없어 해당 에러가 발생한다. 2. example Entity 설정 code // TestEntity.java @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity public class TestEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private int testPriority; } // TestRep..
JPA 낙관적 잠금 (Optimistic locking)을 알아보자 0. 목차 * 이 글은 MySQL을 기본으로 예제 및 시나리오를 작성합니다. 목차 1. 낙관적 잠금이란? 1.1 MySQL 엔진 level과 스토리지 엔진 level MySQL에서 사용되는 잠금은 크게 스토리지 엔진 레벨과 MySQL 엔진 레벨로 나눠볼 수 있다. MySQL 엔진 레벨의 잠금은 모든 스토리지 엔진에 영향을 미치게 되지만 스토리지 엔진 레벨의 잠금은 스토리지 엔진 간 상호 영향을 미치지는 않는다. 낙관적 잠금은 InnoDB 스토리지 엔진 잠금의 한 종류이다. 1.2 비관적 잠금과 낙관적 잠금 1.2.1 비관적 잠금 현재 트랜잭션에서 변경하고자 하는 레코드에 대해 잠금을 획득하고 변경 작업을 처리하는 방식 '변경하고자 하는 레코드를 다른 트랜잭션에서도 변경할 수 있다'라는 비관적인 가정을 하..
[JUnit] 객체 타입 체크 * JUnit5 사용 * 반환된 객체의 타입을 체크해야할 경우가 있다. 1. 시나리오 * 나뭇잎 타입에따라 나무를 분류한다. * 올바른 유형을 반환하는지 검사할 필요가 있다. class TestClass { fun sortTree(name: String): Tree { val deciduous = listOf("Beech", "Birch", "Ash", "Whitebeam", "Hornbeam", "Hazel & Willow") val evergreen = listOf("Cedar", "Holly", "Laurel", "Olive", "Pine") return if(deciduous.contains(name)) { Deciduous(name) } else if(evergreen.contains(name)..
[JUnit] JUnit에서 현재 실행 중인 테스트 이름 가지고 오기 * JUnit5 사용 * TestInfo 객체를 테스트에 주입 가능 1. 개별 테스트 @Test fun givenNumbers_whenOddCheck_thenVerify1(testInfo: TestInfo) { println("displayName = " + testInfo.displayName) val number = 5 assertTrue(TestClass().oddCheck(number)) } * 테스트 이름을 표시하기 위해 인터페이스 TestInfo의 displayName 프로퍼티를 사용 displayName = givenNumbers_whenOddCheck_thenVerify1(TestInfo) 2. Parameterized 테스트 var testInfo: TestInfo? = null @Be..
스프링 빈 생명주기 메서드와 실행 순서 스프링 빈 생명주기 메서드와 실행 순서 스프링 빈(Bean) 생명주기를 담당하는 메소드들을 알아보자 초기화 메소드 빈이 생성 되고 의존성 주입까지 완료된 후에 실행하는 초기화 메서드 @PostConstruct ```java import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Slf4j @Component public class TempBean { @PostConstruct public void postConstruct(){ log.info("@PostConstruct !!!!!!!!"); } } ``` 메서드 선언부에 @PostConstr..
로그아웃 처리 필터: LogoutFilter 로그아웃 처리 필터: LogoutFilter 로그아웃을 처리하는 필터 LogoutHandler : 여러 개의 logoutHandler를 감싸고 있는 Composite 객체 LogoutSuccessHandler : 로그아웃 처리 후 어떻게 할 것인지 정의 기본 LogoutSuccessHandler는 SimpleUrlLogoutSuccessHandler 로그아웃 post 요청시에만 동작함 로그아웃 요청시 LogoutHandler에 기본적으로 등록된 logoutHandler들이 존재 로그아웃 config 설정 * 100 번째 글!!!!!!!!!
Controller Test를 해보자~! 1. Controller Test(Web Layer) 1.1 컨텍스트 로드테스트 컨텍스트가 정상적으로 올라오는지 확인하기 위해 추가 @SpringBootTest class TestingWebApplicationTest { @Autowired private HomeController controller; @Test public void contextLoads() { assertThat(controller).isNotNull(); } } 1.2. Controller Test 1.2.1. HttpRequest Test 프로덕션과 마찬가지로 http 요청을 통해 응답을 확인할 수 있음 실제 서버를 구동시키는 것과 유사하게 테스트 동작 @SpringBootTest(webEnvironment = WebEnviron..
DispatcherServlet 기본 동작 1. DispatcherServlet 기본 동작 get http://localhost:8080/app/hello DispatcherServlet.java doService @Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { logRequest(request); ... doDispatch 로 진입 멀티파트 요청(파일 업로드) 인지 확인 핸들러를 찾아오는 부분 : 해당 요청을 처리하는 핸들러를 찾아오는 부분 (대부분 전략 패턴을 통해 가지고 옴) DispatcherServlet이 들고 있는 여러개의 핸들러 맵핑중 RequestMappingHandlerMappin..
Filter 를 활용한 ACL 만들기 (feat. Spring) 1. 개요 업무를 하던중 컨트롤러 레이어에서 허용된 IP 를 체크하는 로직이 상당수 중복코드로 남아 있는것을 발견함 IP 체크를 통해 허용된 IP가 아니라면 Exception 을 던지고 있었음 허용되지 않은 IP가 접근하는것을 Exception이 아닌 403(forbidden)응답 또는 은닉화를 위해 404(Not Found) 응답을 돌려줘야 된다고 생각함 2. Before 2.1. Code 2.1.1. Controller @RequestMapping(value = "/api/test") public Map apiTest() { // 중복코드 if (!ipInfoService.checkAllowIps()) { throw new RuntimeException( "[" + appProjectName + " ..