クエリN+1問題
1.問題の状況
クエリ
2.原因分析
Board Entity
@OneToOne(mappedby = "board", fetch = FetchType.LAZY)
private Vote vote;
Vote Entity@OneToOne(fetch = FetchType.Lazy)
@JoinColumn(name = "board_id")
private Board board;
@OneToOne(mappedby = "board")
:BoardとVoteをOneToOneとして双方向関連付け(VoteはBoardのFKを含む)fetch = FetchType.LAZY
:Boardは遅延ロードに設定されていますが、5つの取締役会を参照すると、同じ5回の票が得られます.ただし、Voteは所有者であるため、Voteで設定した遅延ロードは変更されないため、Boardはクエリされません.Query X 5
Hibernate:
select
vote0_.id as id1_15_1_,
vote0_.board_id as board_id8_15_1_,
vote0_.chat_room_id as chat_roo9_15_1_,
vote0_.top_pointa as top_poin2_15_1_,
vote0_.top_pointb as top_poin3_15_1_,
vote0_.topicacnt as topicacn4_15_1_,
vote0_.topicbcnt as topicbcn5_15_1_,
vote0_.total_pointa as total_po6_15_1_,
vote0_.total_pointb as total_po7_15_1_,
from
vote vote0_
where
vote0_.board_id=?
3.対策案
Board Entity
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
@JoinColumn(name = "vote")
private Vote vote;
@JoinColumn(name = "vote")
:BoardからVoteを要求する論理が必要であるため、Boardを所有者に設定fetch = FetchType.Lazy
:Boardがマスターであるため、OneToOneには遅延ロード設定が適用されます.Query
Hibernate:
select
board0_.id as id1_1_,
board0_.created_at as created_2_1_,
board0_.modified_at as modified3_1_,
board0_.converted_file_name as converte4_1_,
board0_.file_path as file_pat5_1_,
board0_.topic_a as topic_a6_1_,
board0_.topic_b as topic_b7_1_,
board0_.user_id as user_id9_1_,
board0_.vote as vote10_1_,
board0_.winner as winner8_1_
from
board board0_
order by
board0_.created_at desc limit ?
4.その他の問題
Query X 5
Hibernate:
select
vote0_.id as id1_15_0_,
vote0_.chat_room_id as chat_roo8_15_0_,
vote0_.top_pointa as top_poin2_15_0_,
vote0_.top_pointb as top_poin3_15_0_,
vote0_.topicacnt as topicacn4_15_0_,
vote0_.topicbcnt as topicbcn5_15_0_,
vote0_.total_pointa as total_po6_15_0_,
vote0_.total_pointb as total_po7_15_0_
from
vote vote0_
where
vote0_.id=?
5.その他のトラブルシューティング
batchsizeを
application.yml
default_batch_fetch_size: 10
Query X 1Hibernate:
select
vote0_.id as id1_15_0_,
vote0_.chat_room_id as chat_roo8_15_0_,
vote0_.top_pointa as top_poin2_15_0_,
vote0_.top_pointb as top_poin3_15_0_,
vote0_.topicacnt as topicacn4_15_0_,
vote0_.topicbcnt as topicbcn5_15_0_,
vote0_.total_pointa as total_po6_15_0_,
vote0_.total_pointb as total_po7_15_0_
from
vote vote0_
where
vote0_.id in (
?, ?, ?
)
Reference
この問題について(クエリN+1問題), 我々は、より多くの情報をここで見つけました https://velog.io/@raddaslul/쿼리-N-1-문제-sdemhf15テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol