Skip to content

Commit 9e1ad5a

Browse files
fix(#311): entity 이름 변경: user_tag -> tag_user, brand_tag -> tag_brand (#312)
## Summary Tag_User 엔티티에 isDeprecated가 추가되면서 DB에 반영되지 않아 조회에서 문제가 발생. DB를 업데이트하고, 도메인 별로 다른 Entity라는 것을 명시하기 위해 이름 변경. ## Changes 엔티티 수정: * [TagBrand.java:44](vscode-webview://0rvlkkc586im8avft78fp47jf38ceons5fui8hb1o4ja1l4aqens/entity/src/main/java/com/example/RealMatch/tag/domain/entity/TagBrand.java#L44): 생성자 이름 BrandTag → TagBrand * [Brand.java:130](vscode-webview://0rvlkkc586im8avft78fp47jf38ceons5fui8hb1o4ja1l4aqens/entity/src/main/java/com/example/RealMatch/brand/domain/entity/Brand.java#L130): 메서드 addBrandTag(BrandTag) → addTagBrand(TagBrand) BrandService 수정: * brand.getBrandTags() → brand.getTagsBrand() * brand.addBrandTag(BrandTag.builder()...) → brand.addTagBrand(TagBrand.builder()...) * update 메서드에서 DTO 호출을 getBrandTags()로 통일 ## Type of Change <!-- 해당하는 항목에 x 표시해주세요 --> - [X] Bug fix (기존 기능에 영향을 주지 않는 버그 수정) - [ ] New feature (기존 기능에 영향을 주지 않는 새로운 기능 추가) - [ ] Breaking change (기존 기능에 영향을 주는 수정) - [ ] Refactoring (기능 변경 없는 코드 개선) - [ ] Documentation (문서 수정) - [ ] Chore (빌드, 설정 등 기타 변경) - [ ] Release (develop → main 배포) ## Related Issues #311
1 parent 9a260b2 commit 9e1ad5a

File tree

12 files changed

+186
-181
lines changed

12 files changed

+186
-181
lines changed

data/generators/redis_matching_generator.py

Lines changed: 89 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def generate_brand_documents(self):
115115
# brand_tag 매핑 정보 조회
116116
cursor.execute("""
117117
SELECT bt.brand_id, bt.tag_id, t.tag_type, t.tag_category
118-
FROM brand_tag bt
118+
FROM tag_brand bt
119119
JOIN tag t ON bt.tag_id = t.id
120120
""")
121121
brand_tag_mappings = cursor.fetchall()
@@ -252,90 +252,90 @@ def generate_campaign_documents(self):
252252
print(f"[완료] {count}개의 캠페인 태그 문서 생성 완료")
253253
return count
254254

255-
def generate_user_documents(self):
256-
print("\n[사용자] Redis 사용자 태그 문서 생성 중...")
257-
258-
with self.mysql_conn.cursor() as cursor:
259-
# 사용자 정보 조회
260-
cursor.execute("SELECT id, gender FROM users WHERE role = 'CREATOR' AND is_deleted = FALSE")
261-
users = cursor.fetchall()
262-
263-
# user_tag 매핑 정보 조회
264-
cursor.execute("""
265-
SELECT ut.user_id, ut.tag_id, t.tag_type, t.tag_category
266-
FROM user_tag ut
267-
JOIN tag t ON ut.tag_id = t.id
268-
""")
269-
user_tag_mappings = cursor.fetchall()
270-
271-
if not users:
272-
print("[경고] CREATOR 역할의 사용자가 없습니다.")
273-
return 0
274-
275-
# user_id별 태그 그룹화
276-
user_tags = {}
277-
for mapping in user_tag_mappings:
278-
user_id = mapping['user_id']
279-
if user_id not in user_tags:
280-
user_tags[user_id] = {'패션': [], '뷰티': [], '콘텐츠': []}
281-
tag_type = mapping['tag_type']
282-
if tag_type in user_tags[user_id]:
283-
user_tags[user_id][tag_type].append(mapping['tag_id'])
284-
285-
count = 0
286-
for user in users:
287-
user_id = user['id']
288-
gender = user['gender']
289-
290-
# 성별에 따른 키 범위 조정
291-
if gender == 'MALE':
292-
height = random.randint(165, 185)
293-
top_size = str(random.randint(95, 110))
294-
bottom_size = str(random.randint(30, 36))
295-
elif gender == 'FEMALE':
296-
height = random.randint(155, 175)
297-
top_size = str(random.randint(44, 66))
298-
bottom_size = str(random.randint(24, 30))
299-
else:
300-
height = random.randint(160, 180)
301-
top_size = str(random.randint(50, 100))
302-
bottom_size = str(random.randint(26, 34))
303-
304-
# 해당 사용자의 실제 태그 매핑 사용
305-
user_tag_data = user_tags.get(user_id, {'패션': [], '뷰티': [], '콘텐츠': []})
306-
307-
# 매핑된 태그가 없으면 랜덤 생성
308-
fashion_tags = user_tag_data['패션'] if user_tag_data['패션'] else self._get_random_tag_ids_by_type('패션', 2, 5)
309-
beauty_tags = user_tag_data['뷰티'] if user_tag_data['뷰티'] else self._get_random_tag_ids_by_type('뷰티', 2, 5)
310-
content_tags = user_tag_data['콘텐츠'] if user_tag_data['콘텐츠'] else self._get_random_tag_ids_by_type('콘텐츠', 2, 4)
311-
312-
# 체형 및 기타 태그 ID
313-
body_type_tag = self._get_random_tag_ids(['체형'], 1, 1)
314-
audience_age_tags = self._get_random_tag_ids(['시청자 나이대'], 1, 2)
315-
audience_gender_tags = self._get_random_tag_ids(['시청자 성별'], 1, 2)
316-
video_length_tag = self._get_random_tag_ids(['평균 영상 길이'], 1, 1)
317-
318-
doc = {
319-
'userId': user_id,
320-
'fashionTags': fashion_tags,
321-
'beautyTags': beauty_tags,
322-
'contentTags': content_tags,
323-
'heightTag': height,
324-
'bodyTypeTag': body_type_tag[0] if body_type_tag else None,
325-
'topSizeTag': int(top_size),
326-
'bottomSizeTag': int(bottom_size),
327-
'averageContentsViewsTags': self._get_random_tag_ids(['영상 조회수'], 1, 2),
328-
'contentsAgeTags': audience_age_tags,
329-
'contentsGenderTags': audience_gender_tags,
330-
'contentsLengthTags': video_length_tag,
331-
}
332-
333-
key = f"com.example.RealMatch.match.infrastructure.redis.document.UserTagDocument:user:{user_id}"
334-
self.redis_client.json().set(key, '$', doc)
335-
count += 1
336-
337-
print(f"[완료] {count}개의 사용자 태그 문서 생성 완료")
338-
return count
255+
# def generate_user_documents(self):
256+
# print("\n[사용자] Redis 사용자 태그 문서 생성 중...")
257+
258+
# with self.mysql_conn.cursor() as cursor:
259+
# # 사용자 정보 조회
260+
# cursor.execute("SELECT id, gender FROM users WHERE role = 'CREATOR' AND is_deleted = FALSE")
261+
# users = cursor.fetchall()
262+
263+
# # user_tag 매핑 정보 조회
264+
# cursor.execute("""
265+
# SELECT ut.user_id, ut.tag_id, t.tag_type, t.tag_category
266+
# FROM user_tag ut
267+
# JOIN tag t ON ut.tag_id = t.id
268+
# """)
269+
# user_tag_mappings = cursor.fetchall()
270+
271+
# if not users:
272+
# print("[경고] CREATOR 역할의 사용자가 없습니다.")
273+
# return 0
274+
275+
# # user_id별 태그 그룹화
276+
# user_tags = {}
277+
# for mapping in user_tag_mappings:
278+
# user_id = mapping['user_id']
279+
# if user_id not in user_tags:
280+
# user_tags[user_id] = {'패션': [], '뷰티': [], '콘텐츠': []}
281+
# tag_type = mapping['tag_type']
282+
# if tag_type in user_tags[user_id]:
283+
# user_tags[user_id][tag_type].append(mapping['tag_id'])
284+
285+
# count = 0
286+
# for user in users:
287+
# user_id = user['id']
288+
# gender = user['gender']
289+
290+
# # 성별에 따른 키 범위 조정
291+
# if gender == 'MALE':
292+
# height = random.randint(165, 185)
293+
# top_size = str(random.randint(95, 110))
294+
# bottom_size = str(random.randint(30, 36))
295+
# elif gender == 'FEMALE':
296+
# height = random.randint(155, 175)
297+
# top_size = str(random.randint(44, 66))
298+
# bottom_size = str(random.randint(24, 30))
299+
# else:
300+
# height = random.randint(160, 180)
301+
# top_size = str(random.randint(50, 100))
302+
# bottom_size = str(random.randint(26, 34))
303+
304+
# # 해당 사용자의 실제 태그 매핑 사용
305+
# user_tag_data = user_tags.get(user_id, {'패션': [], '뷰티': [], '콘텐츠': []})
306+
307+
# # 매핑된 태그가 없으면 랜덤 생성
308+
# fashion_tags = user_tag_data['패션'] if user_tag_data['패션'] else self._get_random_tag_ids_by_type('패션', 2, 5)
309+
# beauty_tags = user_tag_data['뷰티'] if user_tag_data['뷰티'] else self._get_random_tag_ids_by_type('뷰티', 2, 5)
310+
# content_tags = user_tag_data['콘텐츠'] if user_tag_data['콘텐츠'] else self._get_random_tag_ids_by_type('콘텐츠', 2, 4)
311+
312+
# # 체형 및 기타 태그 ID
313+
# body_type_tag = self._get_random_tag_ids(['체형'], 1, 1)
314+
# audience_age_tags = self._get_random_tag_ids(['시청자 나이대'], 1, 2)
315+
# audience_gender_tags = self._get_random_tag_ids(['시청자 성별'], 1, 2)
316+
# video_length_tag = self._get_random_tag_ids(['평균 영상 길이'], 1, 1)
317+
318+
# doc = {
319+
# 'userId': user_id,
320+
# 'fashionTags': fashion_tags,
321+
# 'beautyTags': beauty_tags,
322+
# 'contentTags': content_tags,
323+
# 'heightTag': height,
324+
# 'bodyTypeTag': body_type_tag[0] if body_type_tag else None,
325+
# 'topSizeTag': int(top_size),
326+
# 'bottomSizeTag': int(bottom_size),
327+
# 'averageContentsViewsTags': self._get_random_tag_ids(['영상 조회수'], 1, 2),
328+
# 'contentsAgeTags': audience_age_tags,
329+
# 'contentsGenderTags': audience_gender_tags,
330+
# 'contentsLengthTags': video_length_tag,
331+
# }
332+
333+
# key = f"com.example.RealMatch.match.infrastructure.redis.document.UserTagDocument:user:{user_id}"
334+
# self.redis_client.json().set(key, '$', doc)
335+
# count += 1
336+
337+
# print(f"[완료] {count}개의 사용자 태그 문서 생성 완료")
338+
# return count
339339

340340
def clear_redis_documents(self):
341341
print("\n[정리] 기존 Redis 태그 문서 삭제 중...")
@@ -442,13 +442,13 @@ def generate_all(self, clear_existing=True):
442442

443443
brand_count = self.generate_brand_documents()
444444
campaign_count = self.generate_campaign_documents()
445-
user_count = self.generate_user_documents()
445+
# user_count = self.generate_user_documents()
446446

447447
print("\n" + "=" * 60)
448448
print("[완료] Redis 태그 문서 생성 완료!")
449449
print(f" - 브랜드 문서: {brand_count}개")
450450
print(f" - 캠페인 문서: {campaign_count}개")
451-
print(f" - 사용자 문서: {user_count}개")
451+
# print(f" - 사용자 문서: {user_count}개")
452452
print("=" * 60)
453453

454454
except Exception as e:
@@ -497,8 +497,8 @@ def main():
497497
generator.generate_brand_documents()
498498
if args.campaigns:
499499
generator.generate_campaign_documents()
500-
if args.users:
501-
generator.generate_user_documents()
500+
# if args.users:
501+
# generator.generate_user_documents()
502502
else:
503503
# 전체 생성
504504
generator.generate_all(clear_existing=not args.no_clear)

data/generators/tag_generator.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def generate_user_tags(self):
8383
})
8484

8585
sql = """
86-
INSERT IGNORE INTO user_tag (user_id, tag_id, created_at, updated_at)
86+
INSERT IGNORE INTO tag_user (user_id, tag_id, created_at, updated_at)
8787
VALUES (%(user_id)s, %(tag_id)s, %(created_at)s, %(updated_at)s)
8888
"""
8989
self.execute_many(sql, user_tags, "사용자 태그")
@@ -149,7 +149,7 @@ def group_by_category(tags):
149149

150150
if brand_tags:
151151
sql = """
152-
INSERT IGNORE INTO brand_tag (brand_id, tag_id, created_at, updated_at)
152+
INSERT IGNORE INTO tag_brand (brand_id, tag_id, created_at, updated_at)
153153
VALUES (%(brand_id)s, %(tag_id)s, %(created_at)s, %(updated_at)s)
154154
"""
155155
self.execute_many(sql, brand_tags, "브랜드 태그")
@@ -158,7 +158,7 @@ def group_by_category(tags):
158158

159159
def generate_all(self):
160160
self.generate_tags()
161-
self.generate_user_tags()
161+
# self.generate_user_tags()
162162
self.generate_brand_tags()
163163

164164
# generate campign tags?

data/main.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ def _clear_existing_data(self):
4646
'brand_available_sponsor',
4747
'brand_category',
4848
'brand_like',
49-
'user_tag',
50-
'brand_tag',
49+
'tag_user',
50+
'tag_brand',
5151
'tag',
5252
'campaign',
5353
'brand_image',
@@ -138,8 +138,8 @@ def generate_all(self, user_count=50, brand_count=20, campaign_count=30,
138138
business_gen = BusinessGenerator(self.connection)
139139
business_gen.generate_all(applies_per_campaign)
140140

141-
chat_gen = ChatGenerator(self.connection)
142-
chat_gen.generate_all(room_count, messages_per_room)
141+
#chat_gen = ChatGenerator(self.connection)
142+
#chat_gen.generate_all(room_count, messages_per_room)
143143

144144
redis_gen = RedisDataGenerator()
145145
redis_gen.generate_all(clear_existing=True)
@@ -168,9 +168,9 @@ def main():
168168

169169
parser.add_argument('--users', type=int, default=500,
170170
help='생성할 사용자 수 (기본값: 50)')
171-
parser.add_argument('--brands', type=int, default=20000,
171+
parser.add_argument('--brands', type=int, default=2000,
172172
help='생성할 브랜드 수 (기본값: 20)')
173-
parser.add_argument('--campaigns', type=int, default=30000,
173+
parser.add_argument('--campaigns', type=int, default=3000,
174174
help='생성할 캠페인 수 (기본값: 30)')
175175
parser.add_argument('--rooms', type=int, default=2000,
176176
help='생성할 채팅방 수 (기본값: 20)')

src/main/java/com/example/RealMatch/brand/application/service/BrandService.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@
4646
import com.example.RealMatch.global.presentation.advice.ResourceNotFoundException;
4747
import com.example.RealMatch.global.presentation.code.GeneralErrorCode;
4848
import com.example.RealMatch.match.domain.repository.MatchBrandHistoryRepository;
49-
import com.example.RealMatch.tag.domain.entity.BrandTag;
5049
import com.example.RealMatch.tag.domain.entity.Tag;
50+
import com.example.RealMatch.tag.domain.entity.TagBrand;
5151
import com.example.RealMatch.tag.domain.enums.TagCategory;
5252
import com.example.RealMatch.tag.domain.enums.TagType;
5353
import com.example.RealMatch.tag.domain.repository.TagBrandRepository;
@@ -429,7 +429,7 @@ public void updateBeautyBrand(Long brandId, BrandBeautyUpdateRequestDto requestD
429429
);
430430

431431
// 기존 태그 삭제
432-
brand.getBrandTags().clear();
432+
brand.getTagsBrand().clear();
433433

434434
// *** 브랜드 매칭용/상세 페이지용 뷰티 태그 추가 *** //
435435
if (requestDto.getBrandTags() != null) {
@@ -476,7 +476,7 @@ public void updateFashionBrand(Long brandId, BrandFashionUpdateRequestDto reques
476476
);
477477

478478
// 기존 태그 삭제
479-
brand.getBrandTags().clear();
479+
brand.getTagsBrand().clear();
480480

481481
// *** 브랜드 매칭용/상세 페이지용 패션 태그 추가 *** //
482482
if (requestDto.getBrandTags() != null) {
@@ -519,10 +519,10 @@ private void addTagsToBrand(Brand brand, List<String> tagNames, TagType type, St
519519
allTags.addAll(newTags);
520520

521521
for (Tag tag : allTags) {
522-
boolean isAlreadyLinked = brand.getBrandTags().stream()
523-
.anyMatch(bt -> bt.getTag().getId().equals(tag.getId()));
522+
boolean isAlreadyLinked = brand.getTagsBrand().stream()
523+
.anyMatch(tb -> tb.getTag().getId().equals(tag.getId()));
524524
if (!isAlreadyLinked) {
525-
brand.addBrandTag(BrandTag.builder().tag(tag).build());
525+
brand.addTagBrand(TagBrand.builder().tag(tag).build());
526526
}
527527
}
528528
}
@@ -542,10 +542,10 @@ private void addTagsToBrandByIds(Brand brand, List<Integer> tagIds, String categ
542542
for (Tag tag : tags) {
543543
// 해당 카테고리의 태그인지 확인
544544
if (category.equals(tag.getTagCategory())) {
545-
boolean isAlreadyLinked = brand.getBrandTags().stream()
546-
.anyMatch(bt -> bt.getTag().getId().equals(tag.getId()));
545+
boolean isAlreadyLinked = brand.getTagsBrand().stream()
546+
.anyMatch(tb -> tb.getTag().getId().equals(tag.getId()));
547547
if (!isAlreadyLinked) {
548-
brand.addBrandTag(BrandTag.builder().tag(tag).build());
548+
brand.addTagBrand(TagBrand.builder().tag(tag).build());
549549
}
550550
}
551551
}

src/main/java/com/example/RealMatch/brand/domain/entity/Brand.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import com.example.RealMatch.brand.domain.entity.enums.IndustryType;
77
import com.example.RealMatch.global.common.DeleteBaseEntity;
8-
import com.example.RealMatch.tag.domain.entity.BrandTag;
8+
import com.example.RealMatch.tag.domain.entity.TagBrand;
99
import com.example.RealMatch.user.domain.entity.User;
1010

1111
import jakarta.persistence.CascadeType;
@@ -64,7 +64,7 @@ public class Brand extends DeleteBaseEntity {
6464
private User user;
6565

6666
@OneToMany(mappedBy = "brand", cascade = CascadeType.ALL, orphanRemoval = true)
67-
private List<BrandTag> brandTags = new ArrayList<>();
67+
private List<TagBrand> tagsBrand = new ArrayList<>();
6868

6969
@OneToMany(mappedBy = "brand", cascade = CascadeType.ALL, orphanRemoval = true)
7070
private List<BrandCategoryView> brandCategoryViews = new ArrayList<>();
@@ -127,9 +127,9 @@ public void clearContent(Long updatedBy) {
127127
this.updatedBy = updatedBy;
128128
}
129129

130-
public void addBrandTag(BrandTag brandTag) {
131-
brandTags.add(brandTag);
132-
brandTag.setBrand(this);
130+
public void addTagBrand(TagBrand tagBrand) {
131+
tagsBrand.add(tagBrand);
132+
tagBrand.setBrand(this);
133133
}
134134

135135
public void addBrandCategoryView(BrandCategoryView brandCategoryView) {

0 commit comments

Comments
 (0)