일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 자바스크립트
- 파이썬
- 버전관리
- 소프트웨어
- 컴퓨터과학
- 머신러닝
- 사이버보안
- 네트워크보안
- 클라우드컴퓨팅
- 데이터과학
- 2
- 프로그래밍언어
- 데이터베이스
- 자료구조
- I'm Sorry
- 인공지능
- Yes
- 보안
- 빅데이터
- 데이터구조
- 데이터분석
- 프로그래밍
- 컴퓨터공학
- 코딩
- 알고리즘
- 소프트웨어공학
- 딥러닝
- 웹개발
- 컴퓨터비전
- 네트워크
- Today
- Total
스택큐힙리스트
ORM (객체-관계 매핑)에서 "N+1 selects problem"은 무엇인가요? 본문
‘N+1 선택 문제’는 대개 객체-관계 매핑(ORM)에 대한 논의에서 문제로 제기되며, 객체 세계에서는 간단해 보이는 것에 대해 많은 데이터베이스 쿼리를 수행해야하는 문제가 있음을 이해합니다.
이 문제에 대해 더 자세한 설명을 가지고 있는 사람이 있나요?
답변 1
우선, 당신이 Car → 객체(데이터베이스 행)의 집합을 가지고 있다고 가정해봅시다. 각 Car → 객체마다 Wheel 개체(또 다른 행)의 집합을 가지고 있습니다. 다시 말해, Car → → Wheel 는 1:N 관계입니다.
지금, 모든 차를 반복하고, 각각에 대한 바퀴 목록을 출력해야한다고 가정해보자. 순진한 O/R 구현은 다음과 같을 것이다:
SELECT * FROM Cars;
그리고 각각의 Car 에 대해서:
SELECT * FROM Wheel WHERE CarId = ?
다른 말로 하면, 자동차 하나를 선택하고 N개의 추가 선택사항이 있습니다. 여기서 N은 총 자동차 수입니다.
대안으로, 모든 바퀴를 얻을 수 있고 메모리에서 조회를 수행할 수 있습니다.
SELECT * FROM Wheel;
이렇게 하면 데이터베이스와의 여러 라운드트립 수가 N+1에서 2로 줄어듭니다.
대부분의 ORM 도구는 N+1 select를 방지하는 여러 가지 방법을 제공합니다.
참고문헌: Java Persistence with Hibernate, 13장.
답변 2
ORM (Object-Relational Mapping) is a popular approach used in software development to map object-oriented programming languages to relational databases. Despite its popularity, ORM has its fair share of challenges, including the N+1 selects problem.The N+1 selects problem occurs when an ORM framework queries the database multiple times for related data, rather than fetching all the necessary data in a single query. This problem can lead to performance issues, as it requires multiple trips to the database, resulting in increased latency and network overhead.
To illustrate this issue, let's say we have a database containing customers and their orders, and we want to display all orders for all customers. An ORM application might query the customers table first, then make a separate query to fetch the orders for each customer, resulting in N+1 queries, where N is the number of customers.
To address this problem, ORM frameworks provide various solutions, such as eager fetching, lazy loading, and batch fetching. Eager fetching loads all related data in a single query, while lazy loading loads related data only when needed. Batch fetching groups related data and fetches it in a single query.
In conclusion, the N+1 selects problem is a common issue in ORM frameworks that can negatively impact application performance. Understanding the problem and implementing the appropriate solution can help improve the efficiency of database operations.