왜 (fetch = FetchType.LAZY) 사용해야 하는가?

LJM·2023년 4월 9일
0

Spring

목록 보기
10/14

Let’s say that Order and Member have an N:1 relationship. If there is a Member field variable in the Order class, you should use @ManyToOne above the Member field variable. The reason for using (fetch = FetchType.LAZY) when using it is that even if you wrote code that only needs Order data, if you don’t use it, it will also load Member data from the DB. Is this correct?

Yes, your understanding is correct.

When there is a Member field variable in the Order class, and Order and Member have an N:1 relationship, you should use the @ManyToOne annotation above the Member field variable. This tells JPA that there is a many-to-one relationship between Order and Member entities, and JPA will create a foreign key column in the Order table that refers to the primary key of the Member table.

Using (fetch = FetchType.LAZY) with the @ManyToOne annotation specifies that the related Member entity should be fetched lazily. Lazy fetching means that the related Member data will only be loaded from the database when it is explicitly accessed. This can be beneficial for performance, especially when you only need Order data and don't require the related Member data.

If you don't use (fetch = FetchType.LAZY), the default fetching strategy for @ManyToOne relationships is EAGER. This means that JPA will load the related Member data from the database whenever an Order entity is fetched, even if the Member data is not needed. This can lead to unnecessary performance overhead and slow down your application.

profile
게임개발자 백엔드개발자

0개의 댓글