묻고 답해요
129만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결Slack 클론 코딩[백엔드 with NestJS + TypeORM]
OneToMany 관계에서 FK 데이터를 Repository를 이용하여 insert시 오류
우선 제 프로젝트에서 구성하고 있는 DB의 일부분입니다. 간단하게 p_references 와 m_references, 그리고 parts 와 models 테이블에 그림파일의 정보를 가지고 있는 images객체의 배열이 필요한데 mysql이다보니 이걸 다 One to Many로 추가시켰습니다. 여기에 images의 각각 대상 테이블에 대한 FK를 nullable : true 상태로 추가시켰습니다. 물론 이렇게 구성하면 images 테이블안에 적어도 한개의 FK를 포함한 입력값만 허용하도록 Guards 를 추가시켜야 될꺼 같습니만... 간단히 이해도를 위해 설명을 추가한거고요.여기서 문제는 p_references/m_reference 와 images table과 연결 시킬때 원래 계획된 대로 images 테이블 안에 string 이나 int 형식의 column이 추가되는것이 아닌 대상 테이블 객체가 잡히는 문제인데요.entities/images.ts@Entity("Images", { schema: "workplaces" }) export class Images { @PrimaryGeneratedColumn({ type: "int", name: "imageID" }) id: number; @Column('varchar', { name: 'images', nullable: true }) image: string; @Column('bool', { name: 'isOwn', nullable: false, default: false }) isOwn: boolean; @ManyToOne(() => Mreferences, (mreferences) => mreferences.images, { onDelete: "SET NULL", onUpdate: "CASCADE" }) @JoinColumn([{ name: 'modelNumber', referencedColumnName: 'serialNumber' }]) mreferences: Mreferences; @ManyToOne(() => Preferences, (preferences) => preferences.images, { onDelete: "SET NULL", onUpdate: "CASCADE" }) @JoinColumn([{ name: 'partsNumber', referencedColumnName: 'serialNumber' }]) preferences: Preferences; @ManyToOne(() => Parts, (parts) => parts.images, { onDelete: "SET NULL", onUpdate: "CASCADE" }) @JoinColumn([{ name: 'partsID', referencedColumnName: 'id' }]) parts: Parts; @ManyToOne(() => Models, (models) => models.images, { onDelete: "SET NULL", onUpdate: "CASCADE" }) @JoinColumn([{ name: 'modelID', referencedColumnName: 'id' }]) models: Models; }이것이 images entity에서 설정한 코드입니다. 이렇게 해서 자동으로 생성된 DB 의 ERD가 처음에 올린 스샷으로 제대로 의도된대로 생성된걸 확인할 수 있습니다.기본 설명이 너무 길어졌는데, 이제 여기 강의의 "typeorm 쿼리 빌더" 강의에 나온대로 새로운 데이터를 insert 요청이 발생하면 Images Repository를 이용해서 저장을 하려하는데 문제가 발생드려서 문의드립니다.reference-book.service.tsimport { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Mreferences } from '../entities/Mreferences'; import { Repository } from 'typeorm'; import { ReferencebookModelDto } from './dto/referencebook.model.dto'; import { Videos } from '../entities/Videos'; @Injectable() export class ReferenceBookService { constructor( @InjectRepository(Mreferences) private referenceModelRepository: Repository<Mreferences>, @InjectRepository(Images) private imagesRepository: Repository<Images>, ) { } async addReferenceModel(addReferenceModel: ReferencebookModelDto) { const referenceModelBook = new Mreferences(); const referenceModelImages = new Images(); referenceModelBook.serialNumber = addReferenceModel.serialNumber; referenceModelBook.name = addReferenceModel.modelName; referenceModelBook.brands = addReferenceModel.brand; //..... 생략 await this.referenceModelRepository.save(referenceModelBook); } }이렇게 작성시, 아무런 문제 없이 FK관련 column 값들을 제외하곤 이상없이 제대로 DB에 저장이 되는데요. 문젠 FK 관련한 값에서 제대로 작동하지 않습니다.const data = new Images() 로 새로 Images객체를 생성하여, ERD에서 처럼 거기에 등록된 modelNumber 값을 입력한 dto객체의 images.image 값으로 지정해주고 저장하면 될 줄 알았는데 실제 생성된 Images객체엔 modelNumber 문자열이 존재하는 대산 mreferences 객체만이 존재합니다. 강의에서 직접 다룬 프로젝트는 아니지만 제가 강의를 보면서 직접 따라하다 발생한 문제라 강의관련 문의에 올렸습니다.어딘가에서 오류가 있던걸까요? 추가로 혹시나 필요할까 해서 dto 파일도 올립니다/dto/referencebook.model.dto.tsimport { ApiProperty } from "@nestjs/swagger"; import { Images } from "../../entities/Images"; import { Brands, Categories } from "../../common/types/enum.types"; import { Videos } from "../../entities/Videos"; export class ReferencebookModelDto { @ApiProperty({ example: 'WX532433', description: 'Uniq Serial Number', required: true, }) public serialNumber: string; @ApiProperty({ example: 'Aug-23-2023', description: 'Updated Date', required: true, }) public updateDate: Date; @ApiProperty({ example: 'Samsung Dryer', description: 'Model Name', required: true, }) public modelName: string; @ApiProperty({ example: ['afd34323', 'ty23142'], description: 'Serial number List of related parts ', required: false, }) public relatedParts: string[]; @ApiProperty({ example: ['https:/atlanticappliance.com/parts/p?pid=WX532433/image1.jpg'], description: 'Links of own images location', required: false, }) public images: Images[]; @ApiProperty({ example: ['https:/atlanticappliance.com/parts/p?pid=WX532433/video1.mp4'], description: 'Links of own videos location', required: false, }) public videos: Videos[]; @ApiProperty({ example: 'This is a parts for testing model, WX532433', description: 'Scraped description of current product from other sites', required: false, }) public description: string; @ApiProperty({ example: 'Washer', description: 'Product categories', required: true, }) public category: Categories; @ApiProperty({ example: '24Inch', description: 'Product Variant Options', required: false, }) public variant: string; @ApiProperty({ example: '27.7', description: 'Product Weight', required: false, }) public weight: number; @ApiProperty({ example: 21.49, description: 'Product height', required: false, }) public height: number; @ApiProperty({ example: 21.49, description: 'Product width', required: false, }) public width: number; @ApiProperty({ example: 21.49, description: 'Product depth', required: false, }) public depth: number; @ApiProperty({ example: 'Samsung', description: 'Brand', required: false, }) public brand: Brands; }
-
해결됨스프링 MVC 2편 - 백엔드 웹 개발 활용 기술
DB와 Repository의 관계가 궁금합니다.
[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예)[질문 내용]안녕하세요 스프링 MVC 수업을 수강한 학생입니다.Repository와 DB테이블 간에 관계가 궁금해서 질문올립니다.(1) 예를들어 AuthService 가 있을때 UserRepository를 사용하셨는데, 왜 AuthRepository를 만들지 않고 UserRepository를 사용하셨나요? (2) ReservationService를 구현하기 위해 Reservation 이라는 테이블과 ReservationRepostory가 있습니다. 만약 추가적으로 필요한 정보가 User 테이블에 있어서 UserRepository 가 필요하다면, ReservationService가 ReservationRepository와 UserRepository 을 DI 해서 사용ReservationRepository에 User 테이블에 접근하는 Query를 추가하여 사용[ReservationRepository, UserRepository 나눠서 구현 vs ReservationRepository에 추가로 구현]어떤게 맞을까요??아래는 예시코드입니다. @Service @RequiredArgsConstructor public class MyBatisReservationService implements ReservationService { private final ReservationRepository reservationRepository; private final RoomRepository roomRepository; private final RoomKindRepository roomKindRepository; private final PlaceRepository placeRepository; @Service @RequiredArgsConstructor public class MyBatisReservationService implements ReservationService { private final ReservationRepository reservationRepository;감사합니다.
-
미해결실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화
DTO, VO, DAO, Repository에 관련한 질문드립니다.
안녕하세요 강의 정말 유익하게 잘 듣고 있습니다. 실무로 스프링을 접하며 강의를 같이 들으며 진행하고 있는데 들으면서 너무 헷갈리는 부분이 있어 문의드립니다. 1. DTO 와 VO의 차이 그리고 실무에서 어떤경우에 사용하는지 차이 DTO = 전송되는 데이터를 담는 객체 VO = getter/setter 로만 구성된 불변하는 데이터를 담는 객체 라고 표현이 되는데, 너무 와닿지가 않아서 정확한 차이점을 질문드리고 싶습니다. 추가로, 찾아본 예제들에서는 DTO와 VO를 혼합하여 사용하거나 아예 한쪽만 사용하는경우가 혼재되어 많이 헷갈립니다 실무에서는 어떤경우에 어떤 구조체를 사용하는건지 문의드립니다. 2. DAO와 Repository 의 차이점을 문의드립니다. 제가 알기론, 둘다 DB와 소통을 하는 로직을 구현하는건 같지만 DAO는 Data Persistence 를 구체화 한 것이고, 테이블과 더 Low level에서 연관성을 가지고 있고, Repository는 DAO보다 더 High level로 repository안에 여러개의 dao를 사용하여 구현하기도 하는것으로 알고 있습니다. 다만, 예제들을 찾아보면 누구는 DAO로만 구성하여 사용하고, 누구는 Repository만 구현하여 사용하여 실무에서 어떤경우에 DAO와 Repository를 사용하는지가 너무 헷갈립니다. DAO와 Repository가 실무에서 어느때에 사용되는건지 문의도 같이 드리고 싶습니다.
-
미해결풀스택을 위한 도커와 최신 서버 기술(리눅스, nginx, AWS, HTTPS, flask 배포) [풀스택 Part3]
GPG key 설정, repository 등록 문제
- 본 강의 영상 학습 관련 문의에 대해 답변을 드립니다. (어떤 챕터 몇분 몇초를 꼭 기재부탁드립니다)- 이외의 문의등은 평생강의이므로 양해를 부탁드립니다- 현업과 병행하는 관계로 주말/휴가 제외 최대한 3일내로 답변을 드리려 노력하고 있습니다- 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요. 강의 감사히 잘 듣고 있습니다. 강의 환경인 aws ec2의 ubuntu 22.04 에서 실습중입니다. 강의와 다르게 Warning이 뜨는 부분이 있어서 질문드립니다. 1. [2분 51초] 3번 GPG key 설정 문제 - 입력 $ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - - 출력 Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)). OK 2. [3분 18초] 4번 docker repository 등록 문제 - 입력 1차 $ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable" - 입력 2차(게시판 참고) $ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" - 1차, 2차 입력 출력 Description: Archive for codename: focal components: stable More info: https://download.docker.com/linux/ubuntu Adding repository. Press [ENTER] to continue or Ctrl-c to cancel. Adding deb entry to /etc/apt/sources.list.d/archive_uri-https_download_docker_com_linux_ubuntu-jammy.list Adding disabled deb-src entry to /etc/apt/sources.list.d/archive_uri-https_download_docker_com_linux_ubuntu-jammy.list Hit:1 http://ap-northeast-2.ec2.archive.ubuntu.com/ubuntu jammy InRelease Hit:2 http://ap-northeast-2.ec2.archive.ubuntu.com/ubuntu jammy-updates InRelease Hit:3 http://ap-northeast-2.ec2.archive.ubuntu.com/ubuntu jammy-backports InRelease Hit:4 https://download.docker.com/linux/ubuntu jammy InRelease Get:5 https://download.docker.com/linux/ubuntu focal InRelease [57.7 kB] Get:6 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB] Get:7 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages [16.7 kB] Fetched 185 kB in 1s (170 kB/s) Reading package lists... Done W: https://download.docker.com/linux/ubuntu/dists/jammy/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details. W: Skipping acquire of configured file './binary-amd64/Packages' as repository 'https://download.docker.com/linux/ubuntu jammy InRelease' doesn't have the component '.' (component misspelt in sources.list?) W: Skipping acquire of configured file './i18n/Translation-en' as repository 'https://download.docker.com/linux/ubuntu jammy InRelease' doesn't have the component '.' (component misspelt in sources.list?) W: Skipping acquire of configured file './cnf/Commands-amd64' as repository 'https://download.docker.com/linux/ubuntu jammy InRelease' doesn't have the component '.' (component misspelt in sources.list?) W: https://download.docker.com/linux/ubuntu/dists/focal/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details. 위처럼 Warning 문구가 뜨는 이유가 무엇인지 궁금합니다. 그리고 이대로 계속 진행해도 문제는 없을까요? 구글에 검색해봐도 전체적으로 무슨말인지 이해가 가지 않아서.. 상세한 설명 부탁드리겠습니다. 감사합니다.
-
해결됨스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
리포지토리 테스트 질문
현재 11강의 리포지토리 테스트 케이스 작성부분을 하고 있는데 제가 강의 내용과 동일하게 진행을 하고 있었는데 영한님처럼 result = true가 출력이 안되고 저는 result = hello.hellospring.domain.Member@5c671d7f가 출력됩니다. 무엇이 문제일까요??
-
미해결Flutter 중급 1편 - 클린 아키텍처
NoteRepository 추상화 클래스
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요 오준석님, 강의를 듣다가 Repository 추상화객체에 대해서 질문이 생겨서 질문을 남깁니다. 강의에서 NoteRepositoryImpl은 NoteRepository를 implement받아서 사용을 하는데 왜 이렇게 짜는지가 궁금합니다. NoteRepository는 NoteRepositoryImpl만을 위한 추상화객체인데, 여기서밖에 사용을 안하는데 굳이 클래스로 따로 만들 필요가 있는지 의문이 들었습니다. 코드만 더 많이 짜게 되는건 아닌지 의문이 들어서 질문을 남겨봅니다! 오늘도 좋은 하루 되세요! 감사합니다~ :)
-
미해결실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
MemberServiceTest에서 findOne에 대한 질문
[질문 템플릿]1. 강의 내용과 관련된 질문인가요? 예2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? 예3. 질문 잘하기 메뉴얼을 읽어보셨나요? 어디있나요?[질문 내용]MemberServiceTest의 회원가입()에서findOne을 할 때 Service의 findOne이 아닌 Repository의 findOne을 사용하는 이유가 궁금합니다.
-
해결됨실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
DAO와 REPOSITORY의 차이점...
안녕하세요 항상 좋은 강의 제공해주셔서 감사드립니다. 강의를 듣다보니 dao와 repository의 차이점이 궁금해서 질문을 남깁니다. 검색해보니 dao는 data persistence의 추상화 , repository는 collection of objects의 추상화라고 하는데, 사실상 둘의 기능은 비슷하다고 생각합니다. 하지만 둘의 차이를 명확하게 알고 싶어 질문드립니다. 혹시 mybatis를 사용할때 sql과 매핑할때 dao를 사용하고, repository는 엔티티를 영속성 컨텍스트에 영속화 시킬때 사용하는건가요???
-
미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
"레파지토리"가 한국에서 관용적으로 사용하는 "repository"의 발음인가요?
"repository" 발음이 미국 영어식은 "리파지토리"에 가깝고, 한국에서는 "리포지토리"로도 사용하는 것 같은데 (구글에 검색해 본 결과로는요.)강의하시는 분 발음이 계속 "레파지토리"로 가시던데, 이 발음도 한국에서 관용적으로 사용하나요? 아니면 본인 스타일의 발음인가요?
-
미해결실전! Querydsl
사용자 정의 repository의 implementation class들을 더 작은 클래스들로 쪼개는 방법
만약 예를 들어, repository: WorkRepository Custom Repository interface: WorkRepositoryCustom Custom Repository interface Implementation: WorkRepositoryImpl 정도로 구성되 있을 경우, WorkRepositoryImpl (또는 WorkRepositoryCustom interface)가 너무 커져서 별도의 작은 클래스로 쪼개려고 시도중인데요, 추천하실 만한 방법이 있을까요?
-
미해결스프링 핵심 원리 - 기본편
DAO 관련 질문드립니다.
안녕하세요. 김영한님. 수업에 직접적으로 언급된 내용은 아니지만 업무를 하다 궁금한게 생겨 이렇게 질문 드립니다. 현재 회사에서 사용하는 Spring 프로그램이 https://www.egovframe.go.kr/wiki/doku.php?id=egovframework:rte2:psl:dataaccess:mybatisguide "3.1 기존 DAO 형태로 사용하는 경우"를 따르고 있습니다. DAO라고 명시된 파일은 mybatis에 접근하는 sqlSession만 작성해서 return하고, 그 전에 Service에서 모든걸 처리하고 필요한 해당 DAO를 Service가 호출 하여 DB에 접근합니다. 궁금한 부분은 강의에서 언급된 @Repository를 사용한 interface 로 Service에서 필요한 로직을 처리하고, Service 마지막에 sqlSession으로 return 해주것과 큰 차이가 있는지 궁금합니다. 왜 굳이 한번더 감싸(?) 주는지 잘모르겠습니다. 이렇게 구현해야 할 특별한 이유가 있을까요?
-
미해결실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
하나의 Repository에서 2개 이상의 서로 다른 유형의 엔터티를 반환해도 되나요?
안녕하세요. 좋은 강의 덕분에 업무에 많은 도움이 되고 있습니다. 감사합니다. ^^ 다름이아니라, 강의 예제에 나온 repository에서는 보통 한 종류의 엔터티를 반환하는데요. 예를 들면 OrderRepository 에서는 반환값이 Order, List<Order> ItemRepository에서는 Item, List<Item>을 반환합니다. 하지만 OrderRepository에서 Item, List<Item>을 반환하는 경우는 없더군요. 그런데 여러 테이블간에 조인을 거쳐 최종 조회되는 엔터티가 해당 Repository의 엔터티가 아닌 경우, 이럴 때는 어떻게 하는 게 좋을까요? 예를 들면 엔터티 간의 관계가 아래와 같을 때 Order : OrderItem = 1 : N Item : OrderItem = 1 : N Item : ItemCategory = 1 : N Category : ItemCategory = 1 : N Order Id = 100인 Item의 List<Category>를 조회하고자 하는 경우 OrderRepository에서 각 엔터티들의 조인을 거쳐 List<Category>를 반환하는 게 좋을까요? 아니면 각각의 Repository에서 필요한 엔터티를 반환받아 최종적으로 List<Category>를 찾는 것이 좋은가요? 아니면 제 3의 별도의 Repository를 만드는 것이 좋을까요? 여러개의 테이블을 조인하여 한 번의 쿼리로 데이터를 조회하는 것이 더 성능상 이점이 있을 것 같은데요 반면 Repository에서 서로 다른 유형의 엔터티를 반환해도 유지보수에 문제가 없을지 걱정이 듭니다. 김영한님의 조언 부탁드립니다.