프로필사진

Go, Vantage point

가까운 곳을 걷지 않고 서는 먼 곳을 갈 수 없다.


Github | https://github.com/overnew/

Blog | https://everenew.tistory.com/





티스토리 뷰

반응형

 

 

 

 

DB의 핵심은 역시 참조 관계의 설정이다.

 

Spring Data MongoDB는 어노테이션을 통한  참조 관계 맵핑을 지원한다.

이전에는 주로 @DBRef 진행하였지만, Spring Data MongoDB 3.3.0부터 지원하는 @DocumentReference 어노테이션으로 설정해보자.

 

 

 

 

 

 

 

Ingredient 문서가 Recipe를 참조하도록 @DocumentReference를 적용하였다.

MongoDB의 장점은 다른 SQL DB와 다른게 일대 다 매핑을 위해 @OneToMany와 같은 어노테이션 적용이 필요없다는 점이다.

 

 

@DocumentReference 
private List<Recipe> recipes;

 

List로 Recipe를 참조하므로 Ingredient 문서 하나가 여러개의 레시피와 매핑된다.

 

 

 

 

Ingredient 문서들이 이미 DB에 먼저 저장되어 있는 경우를 가정하면,

새로운 Recipe가 추가되어 참조 관계를 설정하는 코드는 다음과 같다.

 

 

public Recipe save(Recipe recipe) {
    Recipe savedRecipe = repository.save(recipe);
	setReferenceWithIngredientsByName(savedRecipe.getIngredientNames(), savedRecipe);

    return savedRecipe;
}

private void setReferenceWithIngredientsByName(String[] ingredientNames, Recipe recipe){
        
   	for (String name:ingredientNames) {	//재료 이름을 통해 레시피와 참조 관계 설정
		template.update(Ingredient.class)
        	.matching(where("name").is(name))
            	.apply(new Update().push("recipes", recipe))
            	.first();
  	}
}

 

 

감자라는 Ingredient가 있을 때, 감자 튀김 Recipe를 추가해 참조를 시키면 다음과 같이 Recipe의 id를 통해 참조 관계가 저장이된다.

 

 

 

 

 

이외의 추가적인 lazy, sort, lookup 기능을 제공하니 아래 공식 문서를 참조하자.

https://docs.spring.io/spring-data/mongodb/docs/3.3.0/reference/html/#mapping-usage.document-references

https://spring.io/blog/2021/11/29/spring-data-mongodb-relation-modelling

 

반응형
댓글
반응형
인기글
Total
Today
Yesterday
«   2024/05   »
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 31
글 보관함