관리 메뉴

HeBhy, since 1983.

자바 팁 기록용 - (Java tips with STS) 본문

Dev/Web

자바 팁 기록용 - (Java tips with STS)

HeBhy 2019. 10. 30. 14:46

1. entity 사용 시, JSON API 등을 주고받을 DB와 관계없는 임시 객체를 별도로 만들지 않고 entity에 몇개만 추가해서 쓰고싶을 때, 변수 앞에 아래 @Transient annotation을 써주면 DB에 기록되지 않고 요긴하게 사용할 수 있다.

public class User {
...
@Transient
private Foo tmpFoo;
}

 

 

2. entity 에 포함된 연결된 객체(@OneToMany, @ManyToMany 등)가 lazy 모드일때, View또는 json 전달 시, Lazy handler 관련 에러 뿜뿜일때 아래 @JsonIgnoreProperties를 class 선언 상단에 써주면 해결. (모두 해결되는건 아니니 아래 3번도 참고.)

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Foo {
...
}

 

 

3. 어느 entity가 self-refrenced(ex- 게시물 entity의 parent, children 등으로 매핑되어 있을때) parent나 children에선 file entity등 값이 json등으로 나오게 하고 싶지 않을때(2번과 연관하여 연결 객체의 lazy entity is not inited error 발생하거나 불필요한 경우) @JsonIgnore 등으로는 자기자신에게 동일하게 적용되므로, parent의 files 객체를 출력 예외로 하고 싶다면 parent 선언 시, @JsonIgnoreProperties annotation을 붙이고 뒤에 parent에서만 제외할 self entity내의 객체(files 등)을 적어주면 됨.

public class Article {

  ...

  @ManyToOne
  @JoinColumn(...)
  @JsonIgnoreProperties({"files"})
  Article parent;
}

 

 

4. 게시글의 content 처럼 대용량 데이터를 lazy 처리하고 싶을때, @OneToOne 매핑 대신 @OneToMany를 사용하면 깔끔하게 해결. 다만 무조건 배열의 0번을 가져와서 써야하지만 0번밖에 없으니 코드가 복잡해지는것보단 크게 불편하진 않음.

 

 

5. 특정 entity에서 json으로 객체를 direct 전달시 에러가 날 때, entity내에 아래 @Override 된 toString함수를 만들면 에러없이 Json string으로 출력 가능.

public class Foo {

  ...

  @Override
  public String toString() {
    String result = null;
    try { result = new ObjectMapper().writeValueAsString(this);  } catch (JsonProcessingException e) { e.printStackTrace(); }
    return result;
  }
}

 

 

6. JPA로 entity를 사용할 경우(without EntityManager), repository에서 가져온 attached된 entity를 원본 detach없이 수정 후 view나 json으로 바로 전달하고 싶은 경우, 아래 함수를 entity 내에 만들어서 객체 복제 -> 조작(수정 또는 삭제) -> view로 전달 해주면 detach없이 전달 가능. (json 또는 얕은복사 둘다 가능. objectMapper를 통한 복사시, @JsonIgnore같은 child들은 무시되니 값을 다 살리려면 얕은복사로 진행.)

https://www.baeldung.com/java-deep-copy   참조
public class Foo {
	
    //...
  
	public Foo copy(boolean isJson) {
		Foo result= new Foo();
    
		if(isJson) {
			try { result= (Foo)(new ObjectMapper().readValue(this.toString(), new TypeReference<Foo>(){})); }
			catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
			result.setOwner(null);    // clone시 소거할 객체들 null 지정후 전달
		} else { BeanUtils.copyProperties(this, result); }   // normal shallow copy
        
		return result;
	}
}

 

Comments