├── .github └── workflows │ ├── pre-release-tagging.yml │ └── pre-release-validation.yml ├── .gitignore ├── LICENSE ├── README.md ├── detector ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src │ └── main │ ├── java │ └── io │ │ └── jeyong │ │ └── detector │ │ ├── annotation │ │ ├── NPlusOneTest.java │ │ ├── NPlusOneTestExtension.java │ │ └── NplusOneTestImportSelector.java │ │ ├── aspect │ │ └── ConnectionProxyAspect.java │ │ ├── config │ │ ├── NPlusOneDetectorBaseConfig.java │ │ ├── NPlusOneDetectorExceptionConfig.java │ │ ├── NPlusOneDetectorLoggingConfig.java │ │ └── NPlusOneDetectorProperties.java │ │ ├── context │ │ ├── ExceptionContext.java │ │ ├── QueryContext.java │ │ └── QueryContextHolder.java │ │ ├── exception │ │ └── NPlusOneQueryException.java │ │ ├── factory │ │ └── ConnectionProxyFactory.java │ │ ├── interceptor │ │ ├── ConnectionCloseInterceptor.java │ │ └── QueryCaptureInspector.java │ │ └── template │ │ ├── NPlusOneQueryCollector.java │ │ ├── NPlusOneQueryLogger.java │ │ └── NPlusOneQueryTemplate.java │ └── resources │ └── META-INF │ └── spring │ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml ├── settings.gradle └── test ├── .gitignore ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── java │ └── io │ │ └── jeyong │ │ └── test │ │ ├── InitData.java │ │ ├── TestApplication.java │ │ ├── case1 │ │ ├── controller │ │ │ ├── AuthorController.http │ │ │ └── AuthorController.java │ │ ├── entity │ │ │ ├── Author.java │ │ │ └── Book.java │ │ ├── repository │ │ │ ├── AuthorRepository.java │ │ │ └── BookRepository.java │ │ └── service │ │ │ ├── AuthorServiceV1.java │ │ │ ├── AuthorServiceV2.java │ │ │ └── AuthorServiceV3.java │ │ ├── case2 │ │ ├── controller │ │ │ ├── ProductController.http │ │ │ └── ProductController.java │ │ ├── entity │ │ │ ├── Order.java │ │ │ └── Product.java │ │ ├── repository │ │ │ ├── OrderRepository.java │ │ │ └── ProductRepository.java │ │ └── service │ │ │ └── ProductService.java │ │ ├── case3 │ │ ├── controller │ │ │ ├── TeamController.http │ │ │ └── TeamController.java │ │ ├── entity │ │ │ ├── Member.java │ │ │ └── Team.java │ │ ├── repository │ │ │ ├── MemberRepository.java │ │ │ └── TeamRepository.java │ │ └── service │ │ │ └── TeamService.java │ │ ├── case4 │ │ ├── controller │ │ │ ├── AddressController.http │ │ │ ├── AddressController.java │ │ │ ├── PersonController.http │ │ │ └── PersonController.java │ │ ├── entity │ │ │ ├── Address.java │ │ │ └── Person.java │ │ ├── repository │ │ │ ├── AddressRepository.java │ │ │ └── PersonRepository.java │ │ └── service │ │ │ ├── AddressService.java │ │ │ └── PersonService.java │ │ └── case5 │ │ ├── controller │ │ ├── CourseController.http │ │ ├── CourseController.java │ │ ├── StudentController.http │ │ └── StudentController.java │ │ ├── entity │ │ ├── Course.java │ │ └── Student.java │ │ ├── repository │ │ ├── CourseRepository.java │ │ └── StudentRepository.java │ │ └── service │ │ ├── CourseService.java │ │ └── StudentService.java └── resources │ ├── application.properties │ └── application.yml └── test └── java └── io └── jeyong └── test └── environment ├── main ├── case1 │ ├── controller │ │ └── AuthorControllerTest.java │ └── service │ │ └── AuthorServiceTest.java ├── case2 │ ├── controller │ │ └── ProductControllerTest.java │ └── service │ │ └── ProductServiceTest.java ├── case3 │ ├── controller │ │ └── TeamControllerTest.java │ └── service │ │ └── TeamServiceTest.java ├── case4 │ ├── controller │ │ ├── AddressControllerTest.java │ │ └── PersonControllerTest.java │ └── service │ │ ├── AddressServiceTest.java │ │ └── PersonServiceTest.java ├── case5 │ ├── controller │ │ ├── CourseControllerTest.java │ │ └── StudentControllerTest.java │ └── service │ │ ├── CourseServiceTest.java │ │ └── StudentServiceTest.java ├── exclude │ └── ExcludeQueryTest.java └── level │ ├── LoggerLevelDebugTest.java │ ├── LoggerLevelErrorTest.java │ ├── LoggerLevelInfoTest.java │ ├── LoggerLevelTraceTest.java │ └── LoggerLevelWarnTest.java ├── test ├── annotation │ └── AnnotationTest.java ├── exclude │ └── ExcludeQueryTest.java └── mode │ ├── configuration │ ├── ExceptionModeConfigurationTest.java │ └── LoggingModeConfigurationTest.java │ ├── integration │ ├── ExceptionModeIntegrationTest.java │ └── LoggingModeIntegrationTest.java │ └── unit │ ├── ExceptionModeUnitTest.java │ ├── LoggingModeUnitTest.java │ └── config │ └── TestInitDataConfig.java └── workbench ├── concurrency └── ExceptionContextConcurrencyTest.java └── performance ├── ExceptionContextPerformanceTest.java └── LoggerPerformanceTest.java /.github/workflows/pre-release-tagging.yml: -------------------------------------------------------------------------------- 1 | name: 'pre-release-tagging' 2 | 3 | on: 4 | pull_request: 5 | types: [closed] 6 | 7 | permissions: write-all 8 | 9 | jobs: 10 | create-tag: 11 | if: github.event.pull_request.merged == true 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Extract version 17 | id: extract_version 18 | run: | 19 | VERSION=$(echo "${{ github.event.pull_request.title }}" | grep -oP '\d+\.\d+\.\d+') 20 | echo "version=$VERSION" >> $GITHUB_OUTPUT 21 | 22 | - name: Create a tag 23 | if: steps.extract_version.outputs.version != '' 24 | uses: rickstaa/action-create-tag@v1 25 | with: 26 | tag: "${{ steps.extract_version.outputs.version }}" 27 | 28 | - name: Output created tag 29 | if: steps.extract_version.outputs.version != '' 30 | run: echo "Created tag v${{ steps.extract_version.outputs.version }}" 31 | -------------------------------------------------------------------------------- /.github/workflows/pre-release-validation.yml: -------------------------------------------------------------------------------- 1 | name: 'pre-release-validation' 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | types: [ opened, synchronize, reopened ] 9 | 10 | permissions: write-all 11 | 12 | jobs: 13 | setup: 14 | runs-on: ubuntu-latest 15 | outputs: 16 | validation-cache-key: ${{ steps.validation-cache.outputs.key }} 17 | steps: 18 | - uses: actions/checkout@v4 19 | 20 | - name: Change directory to test 21 | run: cd test 22 | 23 | - name: Generate validation cache key 24 | id: validation-cache 25 | run: echo "key=$(echo validation-${{ runner.os }}-gradle-${{ hashFiles('test/**/*.gradle*', 'test/**/gradle-wrapper.properties') }})" >> $GITHUB_OUTPUT 26 | 27 | - name: Output start time 28 | shell: bash 29 | run: echo "START_TIME=$(TZ=":Asia/Seoul" date -R|sed 's/.....$//')" 30 | 31 | validation: 32 | needs: setup 33 | runs-on: ubuntu-latest 34 | steps: 35 | - uses: actions/checkout@v4 36 | 37 | - name: Change directory to test 38 | run: cd test 39 | 40 | - name: Cache Gradle packages 41 | id: cache-gradle 42 | uses: actions/cache@v4 43 | with: 44 | path: | 45 | ~/.gradle/caches 46 | ~/.gradle/wrapper 47 | key: ${{ needs.setup.outputs.validation-cache-key }} 48 | restore-keys: | 49 | ${{ runner.os }}-gradle- 50 | 51 | - name: Cache Check 52 | if: steps.cache-gradle.outputs.cache-hit == 'true' 53 | run: echo 'Gradle cache hit!' 54 | 55 | - name: Set up JDK 17 56 | uses: actions/setup-java@v4 57 | with: 58 | java-version: 17 59 | distribution: 'temurin' 60 | 61 | - name: Grant execute permission for gradlew 62 | run: chmod +x ./gradlew 63 | 64 | - name: Run validation 65 | run: ./gradlew test 66 | 67 | - name: Upload validation HTML report 68 | uses: actions/upload-artifact@v4 69 | if: always() 70 | with: 71 | name: validation-report 72 | path: ${{ github.workspace }}/test/build/reports/tests/test/ 73 | 74 | - name: publish validation results 75 | uses: EnricoMi/publish-unit-test-result-action@v2 76 | if: always() 77 | with: 78 | files: ${{ github.workspace }}/test/build/test-results/test/TEST-*.xml 79 | 80 | - name: add comments to a pull request 81 | uses: mikepenz/action-junit-report@v4 82 | if: github.event_name == 'pull_request' && always() 83 | with: 84 | report_paths: ${{ github.workspace }}/test/build/test-results/test/TEST-*.xml 85 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 jeyong 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # N+1 Query Detector for JPA (Hibernate) 2 | 3 | ## ⚙️ Requirements 4 | To use the N+1 Detector, ensure that your project meets the following requirements. 5 | 6 | - **Spring Boot:** 3.0.0 or higher 7 | - **Java:** 17 or higher 8 | - **Hibernate:** 6.x (compatible with Spring Boot 3.x) 9 | 10 | ## 📦 Dependence 11 | To integrate the N+1 Detector into your project, follow the steps below depending on your build tool. 12 | 13 | #### Gradle (build.gradle) 14 | 15 | ``` 16 | repositories { 17 | maven { url 'https://jitpack.io' } 18 | } 19 | 20 | dependencies { 21 | implementation 'com.github.joon6093:jpa-nplus1-detector:2.3.0' 22 | } 23 | ``` 24 | 25 | #### Maven (pom.xml) 26 | 27 | ``` 28 | 29 | 30 | jitpack.io 31 | https://jitpack.io 32 | 33 | 34 | 35 | 36 | com.github.joon6093 37 | jpa-nplus1-detector 38 | 2.3.0 39 | 40 | ``` 41 | 42 | ## 🔧 Configuration 43 | To enable the N+1 Detector, configure the following options in your Spring Boot configuration file. 44 | 45 | #### Options 46 | - **enabled:** Set whether the detector is enabled or disabled (default: false). 47 | - **threshold:** Set the threshold for the number of query executions to detect N+1 queries (default: 2). 48 | - **exclude:** Set the list of specific queries to be excluded from N+1 queries (optional). 49 | - **level:** Set the log level for detected N+1 queries (default: warn). 50 | 51 | #### YAML (application.yml) 52 | ``` 53 | spring: 54 | jpa: 55 | properties: 56 | hibernate: 57 | detector: 58 | enabled: true 59 | threshold: 2 60 | exclude: 61 | - select ... from table1 where ... 62 | - select ... from table2 where ... 63 | level: warn 64 | ``` 65 | 66 | #### Properties (application.properties) 67 | ``` 68 | spring.jpa.properties.hibernate.detector.enabled=true 69 | spring.jpa.properties.hibernate.detector.threshold=2 70 | spring.jpa.properties.hibernate.detector.exclude[0]=select ... from table1 where ... 71 | spring.jpa.properties.hibernate.detector.exclude[1]=select ... from table2 where ... 72 | spring.jpa.properties.hibernate.detector.level=warn 73 | ``` 74 | 75 | ## 📄 Log 76 | When the N+1 Detector is enabled, a startup log shows the activation status, threshold, and log level. 77 | ``` 78 | 2024-08-27T14:59:54.307+09:00 INFO --- i.j.detector.config.NPlusOneDetectorLoggingConfig : N+1 Detector enabled in 'LOGGING' mode. Monitoring queries with a threshold of '2' and logging at 'warn' level. 79 | ``` 80 | 81 | Example log when an N+1 query is detected. 82 | ``` 83 | 2024-08-19T13:04:22.645+09:00 WARN --- i.j.detector.template.NPlusOneQueryLogger : N+1 query detected: 'select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?' was executed 2 times. 84 | ``` 85 | 86 | ## 🔍 Test 87 | The N+1 Detector can be used in test code with two modes, in combination with @SpringBootTest or @DataJpaTest, and any test-specific settings will take precedence over global configuration. 88 | 89 | #### Logging mode 90 | In Logging mode, the N+1 Detector logs detected issues for you to review without interrupting the test flow. 91 | ``` 92 | @NPlusOneTest( 93 | mode = NPlusOneTest.Mode.LOGGING, 94 | threshold = 3, 95 | exclude = { 96 | "select ... from table1 where ...", 97 | "select ... from table2 where ..." 98 | }, 99 | level = Level.DEBUG 100 | ) 101 | @SpringBootTest or @DataJpaTest 102 | class Test { 103 | // Test cases here 104 | } 105 | ``` 106 | 107 | If an N+1 query is detected during test execution, it will be logged as follows. 108 | ``` 109 | 2024-09-20T12:18:19.828+09:00 WARN --- i.j.detector.template.NPlusOneQueryLogger : N+1 query detected: 'select o1_0.id,o1_0.order_number from "order" o1_0 where o1_0.id=?' was executed 3 times. 110 | ``` 111 | 112 | #### Exception mode 113 | In Exception mode, the N+1 Detector throws an exception whenever an N+1 query is detected, enforcing stricter query checks during tests. 114 | ``` 115 | @NPlusOneTest( 116 | mode = NPlusOneTest.Mode.EXCEPTION, 117 | threshold = 5, 118 | exclude = { 119 | "select ... from table1 where ...", 120 | "select ... from table2 where ..." 121 | } 122 | ) 123 | @SpringBootTest or @DataJpaTest 124 | class Test { 125 | // Test cases here 126 | } 127 | ``` 128 | 129 | If an N+1 query is detected during test execution, an exception is thrown. When multiple N+1 exceptions occur within the same test, they are consolidated into a single exception, with additional exceptions being suppressed and thrown together. 130 | ``` 131 | io.jeyong.detector.exception.NPlusOneQueryException: N+1 query detected: 'select o1_0.id,o1_0.order_number from "order" o1_0 where o1_0.id=?' was executed 3 times. 132 | Suppressed: io.jeyong.detector.exception.NPlusOneQueryException: N+1 query detected: 'select a1_0.id,a1_0.city,a1_0.street from address a1_0 where a1_0.id=?' was executed 3 times. 133 | Suppressed: io.jeyong.detector.exception.NPlusOneQueryException: N+1 query detected: 'select p1_0.id,p1_0.address_id,p1_0.name from person p1_0 where p1_0.address_id=?' was executed 3 times. 134 | ``` 135 | 136 | ## ✏️ Note 137 | - Please be aware that the N+1 Query Detector is disabled by default (enabled: false) due to potential performance implications. It is recommended to enable this feature only in your local or development environment to avoid any negative impact on production performance. 138 | - If you encounter any types of N+1 queries that the detector does not catch, please report them by creating an issue in the project repository. This will help us improve the tool by updating and enhancing its detection capabilities. 139 | - If you found this project helpful or interesting, please consider giving it a star on GitHub! ⭐ 140 | 141 | ## 🗓️ Release 142 | - [Version 1.0.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.0.0) - Released on 2024/08/19 143 | - [Version 1.1.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.1.0) - Released on 2024/08/21 144 | - [Version 1.1.1](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.1.1) - Released on 2024/08/24 145 | - [Version 1.1.2](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.1.2) - Released on 2024/08/27 146 | - [Version 1.2.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.2.0) - Released on 2024/08/29 147 | - [Version 1.3.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.3.0) - Released on 2024/09/04 148 | - [Version 1.3.1](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.3.1) - Released on 2024/09/07 149 | - [Version 1.3.2](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.3.2) - Released on 2024/09/16 150 | - [Version 1.4.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/1.4.0) - Released on 2024/09/17 151 | - [Version 2.0.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/2.0.0) - Released on 2024/09/19 152 | - [Version 2.0.1](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/2.0.1) - Released on 2024/09/19 153 | - [Version 2.0.2](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/2.0.2) - Released on 2024/09/20 154 | - [Version 2.1.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/2.1.0) - Released on 2024/09/24 155 | - [Version 2.2.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/2.2.0) - Released on 2024/09/27 156 | - [Version 2.3.0](https://github.com/joon6093/jpa-nplus1-detector/releases/tag/2.3.0) - Released on 2025/04/01 157 | -------------------------------------------------------------------------------- /detector/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /detector/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.0.0' apply false 4 | id 'maven-publish' 5 | } 6 | 7 | group = 'io.jeyong' 8 | version = '2.3.0' 9 | 10 | java { 11 | toolchain { 12 | languageVersion = JavaLanguageVersion.of(17) 13 | } 14 | } 15 | 16 | repositories { 17 | mavenCentral() 18 | maven { url 'https://jitpack.io' } 19 | } 20 | 21 | dependencies { 22 | implementation 'org.springframework.boot:spring-boot-starter:3.0.0' 23 | implementation 'org.hibernate.orm:hibernate-core:6.1.5.Final' 24 | implementation 'org.springframework.boot:spring-boot-starter-aop:3.0.0' 25 | implementation 'org.springframework.boot:spring-boot-starter-test:3.0.0' 26 | } 27 | 28 | publishing { 29 | publications { 30 | mavenJava(MavenPublication) { 31 | from components.java 32 | groupId = project.group 33 | artifactId = 'jpa-nplus1-detector' 34 | version = project.version 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /detector/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joon6093/jpa-nplus1-detector/24cc0b0971c50b145dbdb3d50e8382df644377c6/detector/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /detector/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /detector/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /detector/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/annotation/NPlusOneTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.annotation; 2 | 3 | import io.jeyong.detector.exception.NPlusOneQueryException; 4 | import java.lang.annotation.Documented; 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.slf4j.event.Level; 11 | import org.springframework.context.annotation.EnableAspectJAutoProxy; 12 | import org.springframework.context.annotation.Import; 13 | import org.springframework.core.annotation.AliasFor; 14 | 15 | // @formatter:off 16 | /** 17 | *

18 | * Annotation for enabling the N+1 Detector in JPA (Hibernate). 19 | *

20 | * 21 | *

22 | * To enable the N+1 Detector and customize its behavior, users 23 | * can apply this annotation at the class level to detect and log or throw exceptions 24 | * for N+1 query issues during the execution of test cases. 25 | *

26 | * 27 | * 38 | * 39 | *
40 |  * Example usage:
41 |  * {@code
42 |  * @NPlusOneTest(
43 |  *      mode = NPlusOneTest.Mode.EXCEPTION,
44 |  *      threshold = 5,
45 |  *      exclude = {
46 |  *          "select ... from table1 where ...",
47 |  *          "select ... from table2 where ..."
48 |  *      })
49 |  * @SpringBootTest or @DataJpaTest
50 |  * class MyJpaTest {
51 |  *     // Test cases here
52 |  * }
53 |  * }
54 |  * 
55 | * 56 | *

57 | * This annotation is intended for use in test code only to detect N+1 queries during unit and integration testing. 58 | *

59 | * 60 | * @author jeyong 61 | * @since 2.0 62 | * @see NPlusOneTestExtension 63 | * @see NplusOneTestImportSelector 64 | * @see NPlusOneQueryException 65 | */ 66 | // @formatter:on 67 | @Target(ElementType.TYPE) 68 | @Retention(RetentionPolicy.RUNTIME) 69 | @Documented 70 | @EnableAspectJAutoProxy 71 | @ExtendWith(NPlusOneTestExtension.class) 72 | @Import(NplusOneTestImportSelector.class) 73 | public @interface NPlusOneTest { 74 | 75 | @AliasFor("mode") 76 | Mode value() default Mode.LOGGING; 77 | 78 | @AliasFor("value") 79 | Mode mode() default Mode.LOGGING; 80 | 81 | enum Mode { 82 | LOGGING, 83 | EXCEPTION 84 | } 85 | 86 | int threshold() default 2; 87 | 88 | String[] exclude() default {}; 89 | 90 | Level level() default Level.WARN; 91 | } 92 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/annotation/NPlusOneTestExtension.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.annotation; 2 | 3 | import io.jeyong.detector.context.ExceptionContext; 4 | import io.jeyong.detector.context.QueryContextHolder; 5 | import org.junit.jupiter.api.extension.AfterEachCallback; 6 | import org.junit.jupiter.api.extension.BeforeAllCallback; 7 | import org.junit.jupiter.api.extension.BeforeEachCallback; 8 | import org.junit.jupiter.api.extension.ExtensionContext; 9 | import org.springframework.beans.BeansException; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.test.context.junit.jupiter.SpringExtension; 12 | 13 | public final class NPlusOneTestExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback { 14 | 15 | private ExceptionContext exceptionContext; 16 | 17 | @Override 18 | public void beforeAll(final ExtensionContext extensionContext) { 19 | final ApplicationContext applicationContext = SpringExtension.getApplicationContext(extensionContext); 20 | exceptionContext = getExceptionContext(applicationContext); 21 | } 22 | 23 | private ExceptionContext getExceptionContext(final ApplicationContext applicationContext) { 24 | try { 25 | return applicationContext.getBean(ExceptionContext.class); 26 | } catch (BeansException e) { 27 | return null; 28 | } 29 | } 30 | 31 | @Override 32 | public void beforeEach(final ExtensionContext extensionContext) { 33 | QueryContextHolder.clearContext(); 34 | if (exceptionContext != null) { 35 | exceptionContext.clearContext(); 36 | } 37 | } 38 | 39 | @Override 40 | public void afterEach(final ExtensionContext extensionContext) { 41 | if (exceptionContext == null) { 42 | return; 43 | } 44 | try { 45 | exceptionContext.getContext().ifPresent(exception -> { 46 | throw exception; 47 | }); 48 | } finally { 49 | exceptionContext.clearContext(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/annotation/NplusOneTestImportSelector.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.annotation; 2 | 3 | import io.jeyong.detector.annotation.NPlusOneTest.Mode; 4 | import io.jeyong.detector.config.NPlusOneDetectorExceptionConfig; 5 | import io.jeyong.detector.config.NPlusOneDetectorLoggingConfig; 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | import java.util.Objects; 9 | import org.slf4j.event.Level; 10 | import org.springframework.context.EnvironmentAware; 11 | import org.springframework.context.annotation.ImportSelector; 12 | import org.springframework.core.env.ConfigurableEnvironment; 13 | import org.springframework.core.env.Environment; 14 | import org.springframework.core.env.MapPropertySource; 15 | import org.springframework.core.type.AnnotationMetadata; 16 | import org.springframework.lang.NonNull; 17 | 18 | public final class NplusOneTestImportSelector implements ImportSelector, EnvironmentAware { 19 | 20 | private ConfigurableEnvironment environment; 21 | 22 | @Override 23 | public void setEnvironment(@NonNull final Environment environment) { 24 | this.environment = (ConfigurableEnvironment) environment; 25 | } 26 | 27 | @NonNull 28 | @Override 29 | public String[] selectImports(final AnnotationMetadata importingClassMetadata) { 30 | final Map attributes = Objects.requireNonNull( 31 | importingClassMetadata.getAnnotationAttributes(NPlusOneTest.class.getName()), 32 | "Attributes for @NPlusOneTest cannot be null" 33 | ); 34 | 35 | final Mode mode = (Mode) attributes.get("mode"); 36 | 37 | if (mode == Mode.LOGGING) { 38 | configureForLoggingMode(attributes); 39 | return new String[]{NPlusOneDetectorLoggingConfig.class.getName()}; 40 | } else if (mode == Mode.EXCEPTION) { 41 | configureForExceptionMode(attributes); 42 | return new String[]{NPlusOneDetectorExceptionConfig.class.getName()}; 43 | } else { 44 | throw new IllegalArgumentException("Invalid mode provided for @NPlusOneTest: " + mode); 45 | } 46 | } 47 | 48 | private void configureForLoggingMode(final Map attributes) { 49 | final int threshold = (int) attributes.get("threshold"); 50 | final String[] exclude = (String[]) attributes.get("exclude"); 51 | final Level level = (Level) attributes.get("level"); 52 | 53 | final Map propertyMap = createBasePropertyMap(threshold, exclude); 54 | propertyMap.put("spring.jpa.properties.hibernate.detector.enabled", "true"); 55 | propertyMap.put("spring.jpa.properties.hibernate.detector.level", level.toString()); 56 | 57 | environment.getPropertySources().addFirst(new MapPropertySource("DetectorProperties", propertyMap)); 58 | } 59 | 60 | private void configureForExceptionMode(final Map attributes) { 61 | final int threshold = (int) attributes.get("threshold"); 62 | final String[] exclude = (String[]) attributes.get("exclude"); 63 | 64 | final Map propertyMap = createBasePropertyMap(threshold, exclude); 65 | propertyMap.put("spring.jpa.properties.hibernate.detector.enabled", "false"); 66 | 67 | environment.getPropertySources().addFirst(new MapPropertySource("DetectorProperties", propertyMap)); 68 | } 69 | 70 | private Map createBasePropertyMap(final int threshold, final String[] exclude) { 71 | final Map propertyMap = new HashMap<>(); 72 | propertyMap.put("spring.jpa.properties.hibernate.detector.threshold", String.valueOf(threshold)); 73 | for (int i = 0; i < exclude.length; i++) { 74 | propertyMap.put("spring.jpa.properties.hibernate.detector.exclude[" + i + "]", exclude[i]); 75 | } 76 | return propertyMap; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/aspect/ConnectionProxyAspect.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.aspect; 2 | 3 | import io.jeyong.detector.factory.ConnectionProxyFactory; 4 | import io.jeyong.detector.template.NPlusOneQueryTemplate; 5 | import java.sql.Connection; 6 | import org.aspectj.lang.ProceedingJoinPoint; 7 | import org.aspectj.lang.annotation.Around; 8 | import org.aspectj.lang.annotation.Aspect; 9 | 10 | @Aspect 11 | public final class ConnectionProxyAspect { 12 | 13 | private final NPlusOneQueryTemplate nPlusOneQueryTemplate; 14 | 15 | public ConnectionProxyAspect(final NPlusOneQueryTemplate nPlusOneQueryTemplate) { 16 | this.nPlusOneQueryTemplate = nPlusOneQueryTemplate; 17 | } 18 | 19 | @Around("execution(* javax.sql.DataSource.getConnection())") 20 | public Object wrapConnectionWithProxy(final ProceedingJoinPoint joinPoint) throws Throwable { 21 | final Connection originalConnection = (Connection) joinPoint.proceed(); 22 | return ConnectionProxyFactory.createProxy(originalConnection, nPlusOneQueryTemplate::handleQueryContext); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/config/NPlusOneDetectorBaseConfig.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.config; 2 | 3 | import static org.hibernate.cfg.AvailableSettings.STATEMENT_INSPECTOR; 4 | 5 | import io.jeyong.detector.aspect.ConnectionProxyAspect; 6 | import io.jeyong.detector.interceptor.QueryCaptureInspector; 7 | import io.jeyong.detector.template.NPlusOneQueryTemplate; 8 | import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer; 9 | import org.springframework.context.annotation.Bean; 10 | 11 | public abstract class NPlusOneDetectorBaseConfig { 12 | 13 | @Bean 14 | public ConnectionProxyAspect connectionProxyAspect(final NPlusOneQueryTemplate nPlusOneQueryTemplate) { 15 | return new ConnectionProxyAspect(nPlusOneQueryTemplate); 16 | } 17 | 18 | @Bean 19 | public QueryCaptureInspector queryCaptureInspector() { 20 | return new QueryCaptureInspector(); 21 | } 22 | 23 | @Bean 24 | public HibernatePropertiesCustomizer hibernatePropertiesCustomizer( 25 | final QueryCaptureInspector queryCaptureInspector) { 26 | return hibernateProperties -> hibernateProperties.put(STATEMENT_INSPECTOR, queryCaptureInspector); 27 | } 28 | 29 | public abstract NPlusOneQueryTemplate nPlusOneQueryTemplate(); 30 | } 31 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/config/NPlusOneDetectorExceptionConfig.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.config; 2 | 3 | import io.jeyong.detector.annotation.NPlusOneTest.Mode; 4 | import io.jeyong.detector.context.ExceptionContext; 5 | import io.jeyong.detector.template.NPlusOneQueryCollector; 6 | import io.jeyong.detector.template.NPlusOneQueryTemplate; 7 | import jakarta.annotation.PostConstruct; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | 14 | @Configuration 15 | @EnableConfigurationProperties(NPlusOneDetectorProperties.class) 16 | public class NPlusOneDetectorExceptionConfig extends NPlusOneDetectorBaseConfig { 17 | 18 | private static final Logger logger = LoggerFactory.getLogger(NPlusOneDetectorExceptionConfig.class); 19 | private final NPlusOneDetectorProperties nPlusOneDetectorProperties; 20 | 21 | public NPlusOneDetectorExceptionConfig(final NPlusOneDetectorProperties nPlusOneDetectorProperties) { 22 | this.nPlusOneDetectorProperties = nPlusOneDetectorProperties; 23 | } 24 | 25 | @PostConstruct 26 | public void logInitialization() { 27 | logger.info( 28 | "N+1 Detector enabled in '{}' mode. Monitoring queries with a threshold of '{}'.", 29 | Mode.EXCEPTION, 30 | nPlusOneDetectorProperties.getThreshold()); 31 | } 32 | 33 | @Bean 34 | public ExceptionContext exceptionContext() { 35 | return new ExceptionContext(); 36 | } 37 | 38 | @Bean 39 | @Override 40 | public NPlusOneQueryTemplate nPlusOneQueryTemplate() { 41 | return new NPlusOneQueryCollector( 42 | nPlusOneDetectorProperties.getThreshold(), 43 | nPlusOneDetectorProperties.getExclude(), 44 | exceptionContext()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/config/NPlusOneDetectorLoggingConfig.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.config; 2 | 3 | import io.jeyong.detector.annotation.NPlusOneTest.Mode; 4 | import io.jeyong.detector.template.NPlusOneQueryLogger; 5 | import io.jeyong.detector.template.NPlusOneQueryTemplate; 6 | import jakarta.annotation.PostConstruct; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 10 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | 14 | @Configuration 15 | @ConditionalOnProperty( 16 | prefix = "spring.jpa.properties.hibernate.detector", 17 | name = "enabled", 18 | havingValue = "true", 19 | matchIfMissing = false 20 | ) 21 | @EnableConfigurationProperties(NPlusOneDetectorProperties.class) 22 | public class NPlusOneDetectorLoggingConfig extends NPlusOneDetectorBaseConfig { 23 | 24 | private static final Logger logger = LoggerFactory.getLogger(NPlusOneDetectorLoggingConfig.class); 25 | private final NPlusOneDetectorProperties nPlusOneDetectorProperties; 26 | 27 | public NPlusOneDetectorLoggingConfig(final NPlusOneDetectorProperties nPlusOneDetectorProperties) { 28 | this.nPlusOneDetectorProperties = nPlusOneDetectorProperties; 29 | } 30 | 31 | @PostConstruct 32 | public void logInitialization() { 33 | logger.info( 34 | "N+1 Detector enabled in '{}' mode. Monitoring queries with a threshold of '{}' and logging at '{}' level.", 35 | Mode.LOGGING, 36 | nPlusOneDetectorProperties.getThreshold(), 37 | nPlusOneDetectorProperties.getLevel().toString().toLowerCase()); 38 | } 39 | 40 | @Bean 41 | @Override 42 | public NPlusOneQueryTemplate nPlusOneQueryTemplate() { 43 | return new NPlusOneQueryLogger( 44 | nPlusOneDetectorProperties.getThreshold(), 45 | nPlusOneDetectorProperties.getExclude(), 46 | nPlusOneDetectorProperties.getLevel()); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/config/NPlusOneDetectorProperties.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.config; 2 | 3 | import java.util.List; 4 | import org.slf4j.event.Level; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | 7 | // @formatter:off 8 | /** 9 | *

10 | * Configuration properties for the N+1 Detector in JPA (Hibernate). 11 | *

12 | * 13 | *

14 | * To enable the N+1 Detector and customize its behavior, users 15 | * can configure the following properties in the application configuration 16 | * (e.g., application.yml or application.properties): 17 | *

18 | * 19 | *
    20 | *
  • spring.jpa.properties.hibernate.detector.enabled: Set whether the detector is enabled or disabled (default: false).
  • 21 | *
  • spring.jpa.properties.hibernate.detector.threshold: Set the threshold for the number of query executions to detect N+1 queries (default: 2).
  • 22 | *
  • spring.jpa.properties.hibernate.detector.exclude: Set the list of specific queries to be excluded from N+1 queries (optional).
  • 23 | *
  • spring.jpa.properties.hibernate.detector.level: Set the log level for detected N+1 queries (default: WARN).
  • 24 | *
25 | * 26 | *
 27 |  * Example configuration (YAML):
 28 |  * {@code
 29 |  * spring:
 30 |  *   jpa:
 31 |  *     properties:
 32 |  *       hibernate:
 33 |  *         detector:
 34 |  *           enabled: true
 35 |  *           threshold: 2
 36 |  *           exclude:
 37 |  *             - select ... from table1 where ...
 38 |  *             - select ... from table2 where ...
 39 |  *           level: warn
 40 |  * }
 41 |  * 
42 | * 43 | *
 44 |  * Example configuration (Properties):
 45 |  * {@code
 46 |  * spring.jpa.properties.hibernate.detector.enabled=true
 47 |  * spring.jpa.properties.hibernate.detector.threshold=2
 48 |  * spring.jpa.properties.hibernate.detector.exclude[0]=select ... from table1 where ...
 49 |  * spring.jpa.properties.hibernate.detector.exclude[1]=select ... from table2 where ...
 50 |  * spring.jpa.properties.hibernate.detector.level=warn
 51 |  * }
 52 |  * 
53 | * 54 | *

55 | * The N+1 Detector is disabled by default to avoid potential performance overhead in production environments. 56 | * It is recommended to enable it only in development or testing environments. 57 | *

58 | * 59 | * @author jeyong 60 | * @since 1.0 61 | * @see NPlusOneDetectorBaseConfig 62 | * @see NPlusOneDetectorLoggingConfig 63 | * @see NPlusOneDetectorExceptionConfig 64 | */ 65 | // @formatter:on 66 | @ConfigurationProperties(prefix = "spring.jpa.properties.hibernate.detector") 67 | public class NPlusOneDetectorProperties { 68 | 69 | private boolean enabled = false; 70 | 71 | private int threshold = 2; 72 | 73 | private List exclude = List.of(); 74 | 75 | private Level level = Level.WARN; 76 | 77 | public boolean isEnabled() { 78 | return enabled; 79 | } 80 | 81 | public void setEnabled(final boolean enabled) { 82 | this.enabled = enabled; 83 | } 84 | 85 | public int getThreshold() { 86 | return threshold; 87 | } 88 | 89 | public void setThreshold(final int threshold) { 90 | this.threshold = threshold; 91 | } 92 | 93 | public List getExclude() { 94 | return exclude; 95 | } 96 | 97 | public void setExclude(final List exclude) { 98 | this.exclude = exclude; 99 | } 100 | 101 | public Level getLevel() { 102 | return level; 103 | } 104 | 105 | public void setLevel(final Level level) { 106 | this.level = level; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/context/ExceptionContext.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.context; 2 | 3 | import io.jeyong.detector.exception.NPlusOneQueryException; 4 | import java.util.Optional; 5 | import java.util.concurrent.atomic.AtomicReference; 6 | 7 | public final class ExceptionContext { 8 | 9 | private final AtomicReference primaryException = new AtomicReference<>(); 10 | 11 | public void saveException(final NPlusOneQueryException nPlusOneQueryException) { 12 | primaryException.updateAndGet(existingException -> { 13 | if (existingException != null) { 14 | existingException.addSuppressed(nPlusOneQueryException); 15 | return existingException; 16 | } 17 | 18 | return nPlusOneQueryException; 19 | }); 20 | } 21 | 22 | public Optional getContext() { 23 | return Optional.ofNullable(primaryException.get()); 24 | } 25 | 26 | public void clearContext() { 27 | primaryException.set(null); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/context/QueryContext.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.context; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public final class QueryContext { 7 | 8 | private final Map queryCounts = new HashMap<>(); 9 | 10 | QueryContext() { 11 | } 12 | 13 | void incrementQueryCount(final String query) { 14 | queryCounts.put(query, queryCounts.getOrDefault(query, 0L) + 1); 15 | } 16 | 17 | public Map getQueryCounts() { 18 | return Map.copyOf(queryCounts); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/context/QueryContextHolder.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.context; 2 | 3 | public final class QueryContextHolder { 4 | 5 | private static final ThreadLocal queryContextThreadLocal = 6 | ThreadLocal.withInitial(QueryContext::new); 7 | 8 | private QueryContextHolder() { 9 | } 10 | 11 | public static void saveQuery(final String query) { 12 | queryContextThreadLocal.get().incrementQueryCount(query); 13 | } 14 | 15 | public static QueryContext getContext() { 16 | return queryContextThreadLocal.get(); 17 | } 18 | 19 | public static void clearContext() { 20 | queryContextThreadLocal.remove(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/exception/NPlusOneQueryException.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.exception; 2 | 3 | public class NPlusOneQueryException extends RuntimeException { 4 | 5 | public NPlusOneQueryException(final String query, final Long count) { 6 | super(String.format("N+1 query detected: '%s' was executed %d times.", query, count)); 7 | } 8 | 9 | public NPlusOneQueryException(String message, Throwable cause) { 10 | super(message, cause); 11 | } 12 | 13 | public NPlusOneQueryException(String message) { 14 | super(message); 15 | } 16 | 17 | public NPlusOneQueryException(Throwable cause) { 18 | super(cause); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/factory/ConnectionProxyFactory.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.factory; 2 | 3 | import io.jeyong.detector.interceptor.ConnectionCloseInterceptor; 4 | import java.sql.Connection; 5 | import org.springframework.aop.framework.ProxyFactory; 6 | import org.springframework.aop.support.DefaultPointcutAdvisor; 7 | import org.springframework.aop.support.NameMatchMethodPointcut; 8 | 9 | public final class ConnectionProxyFactory { 10 | 11 | private static final String CLOSE_METHOD_NAME = "close"; 12 | 13 | private ConnectionProxyFactory() { 14 | } 15 | 16 | public static Connection createProxy(final Connection originalConnection, final Runnable onClose) { 17 | final ProxyFactory proxyFactory = new ProxyFactory(originalConnection); 18 | proxyFactory.setInterfaces(Connection.class); 19 | 20 | final NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut(); 21 | pointcut.setMappedName(CLOSE_METHOD_NAME); 22 | 23 | final DefaultPointcutAdvisor advisor = 24 | new DefaultPointcutAdvisor(pointcut, new ConnectionCloseInterceptor(onClose)); 25 | proxyFactory.addAdvisor(advisor); 26 | 27 | return (Connection) proxyFactory.getProxy(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/interceptor/ConnectionCloseInterceptor.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.interceptor; 2 | 3 | import org.aopalliance.intercept.MethodInterceptor; 4 | import org.aopalliance.intercept.MethodInvocation; 5 | 6 | public final class ConnectionCloseInterceptor implements MethodInterceptor { 7 | 8 | private final Runnable onClose; 9 | 10 | public ConnectionCloseInterceptor(final Runnable onClose) { 11 | this.onClose = onClose; 12 | } 13 | 14 | @Override 15 | public Object invoke(final MethodInvocation invocation) throws Throwable { 16 | onClose.run(); 17 | return invocation.proceed(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/interceptor/QueryCaptureInspector.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.interceptor; 2 | 3 | import io.jeyong.detector.context.QueryContextHolder; 4 | import org.hibernate.resource.jdbc.spi.StatementInspector; 5 | 6 | public final class QueryCaptureInspector implements StatementInspector { 7 | 8 | @Override 9 | public String inspect(final String query) { 10 | QueryContextHolder.saveQuery(query); 11 | return query; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/template/NPlusOneQueryCollector.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.template; 2 | 3 | import io.jeyong.detector.context.ExceptionContext; 4 | import io.jeyong.detector.exception.NPlusOneQueryException; 5 | import java.util.List; 6 | 7 | public final class NPlusOneQueryCollector extends NPlusOneQueryTemplate { 8 | 9 | private final ExceptionContext exceptionContext; 10 | 11 | public NPlusOneQueryCollector(final int threshold, final List exclude, 12 | final ExceptionContext exceptionContext) { 13 | super(threshold, exclude); 14 | this.exceptionContext = exceptionContext; 15 | } 16 | 17 | @Override 18 | protected void handleDetectedNPlusOneQuery(final String query, final Long count) { 19 | exceptionContext.saveException(new NPlusOneQueryException(query, count)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/template/NPlusOneQueryLogger.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.template; 2 | 3 | import java.util.List; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.slf4j.event.Level; 7 | 8 | public final class NPlusOneQueryLogger extends NPlusOneQueryTemplate { 9 | 10 | private static final Logger logger = LoggerFactory.getLogger(NPlusOneQueryLogger.class); 11 | private final Level level; 12 | 13 | public NPlusOneQueryLogger(final int threshold, final List exclude, final Level level) { 14 | super(threshold, exclude); 15 | this.level = level; 16 | } 17 | 18 | @Override 19 | protected void handleDetectedNPlusOneQuery(final String query, final Long count) { 20 | if (level == Level.WARN && logger.isWarnEnabled()) { 21 | logger.warn("N+1 query detected: '{}' was executed {} times.", query, count); 22 | } else if (level == Level.TRACE && logger.isTraceEnabled()) { 23 | logger.trace("N+1 query detected: '{}' was executed {} times.", query, count); 24 | } else if (level == Level.INFO && logger.isInfoEnabled()) { 25 | logger.info("N+1 query detected: '{}' was executed {} times.", query, count); 26 | } else if (level == Level.DEBUG && logger.isDebugEnabled()) { 27 | logger.debug("N+1 query detected: '{}' was executed {} times.", query, count); 28 | } else if (level == Level.ERROR && logger.isErrorEnabled()) { 29 | logger.error("N+1 query detected: '{}' was executed {} times.", query, count); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /detector/src/main/java/io/jeyong/detector/template/NPlusOneQueryTemplate.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.detector.template; 2 | 3 | import io.jeyong.detector.context.QueryContextHolder; 4 | import java.util.List; 5 | 6 | public abstract class NPlusOneQueryTemplate { 7 | 8 | private static final String SELECT_KEYWORD = "select"; 9 | private static final String IN_CLAUSE_KEYWORD = " in("; 10 | 11 | private final int threshold; 12 | private final List exclude; 13 | 14 | public NPlusOneQueryTemplate(final int threshold, final List exclude) { 15 | this.threshold = threshold; 16 | this.exclude = exclude; 17 | } 18 | 19 | public final void handleQueryContext() { 20 | try { 21 | QueryContextHolder.getContext().getQueryCounts().forEach((query, count) -> { 22 | if (isValidQuery(query, count)) { 23 | handleDetectedNPlusOneQuery(query, count); 24 | } 25 | }); 26 | } finally { 27 | QueryContextHolder.clearContext(); 28 | } 29 | } 30 | 31 | private boolean isValidQuery(final String query, final Long count) { 32 | return isSelectQuery(query) 33 | && !isBatchSizeQuery(query) 34 | && isExceedingThreshold(count) 35 | && !isExcludedQuery(query); 36 | } 37 | 38 | private boolean isSelectQuery(final String query) { 39 | return query.stripLeading().startsWith(SELECT_KEYWORD); 40 | } 41 | 42 | private boolean isBatchSizeQuery(final String query) { 43 | return query.contains(IN_CLAUSE_KEYWORD); 44 | } 45 | 46 | private boolean isExceedingThreshold(final Long count) { 47 | return count >= threshold; 48 | } 49 | 50 | private boolean isExcludedQuery(final String query) { 51 | return exclude.stream().anyMatch(query::equals); 52 | } 53 | 54 | protected abstract void handleDetectedNPlusOneQuery(final String query, final Long count); 55 | } 56 | -------------------------------------------------------------------------------- /detector/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports: -------------------------------------------------------------------------------- 1 | io.jeyong.detector.config.NPlusOneDetectorLoggingConfig 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joon6093/jpa-nplus1-detector/24cc0b0971c50b145dbdb3d50e8382df644377c6/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | jdk: 2 | - openjdk17 3 | 4 | before_install: 5 | - sdk install java 17.0.2-zulu 6 | - sdk use java 17.0.2-zulu 7 | - sdk install maven 8 | - mvn -v 9 | 10 | install: 11 | - chmod +x ./detector/gradlew 12 | - ./detector/gradlew build publishToMavenLocal 13 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'jpa-nplus1-detector' 2 | 3 | include('detector') 4 | include('test') 5 | -------------------------------------------------------------------------------- /test/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /test/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.0.0' 4 | id 'io.spring.dependency-management' version '1.1.0' 5 | } 6 | 7 | group = 'io.jeyong' 8 | version = '0.0.1-SNAPSHOT' 9 | 10 | java { 11 | toolchain { 12 | languageVersion = JavaLanguageVersion.of(17) 13 | } 14 | } 15 | 16 | repositories { 17 | mavenCentral() 18 | } 19 | 20 | dependencies { 21 | implementation project(':detector') 22 | implementation 'org.springframework.boot:spring-boot-starter-web' 23 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 24 | implementation 'com.h2database:h2' 25 | implementation 'org.projectlombok:lombok' 26 | annotationProcessor 'org.projectlombok:lombok' 27 | 28 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 29 | testRuntimeOnly 'org.junit.platform:junit-platform-launcher' 30 | } 31 | 32 | tasks.named('test') { 33 | useJUnitPlatform() 34 | } 35 | -------------------------------------------------------------------------------- /test/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joon6093/jpa-nplus1-detector/24cc0b0971c50b145dbdb3d50e8382df644377c6/test/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /test/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /test/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /test/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/InitData.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test; 2 | 3 | import io.jeyong.test.case1.entity.Author; 4 | import io.jeyong.test.case1.entity.Book; 5 | import io.jeyong.test.case1.repository.AuthorRepository; 6 | import io.jeyong.test.case1.repository.BookRepository; 7 | import io.jeyong.test.case2.entity.Order; 8 | import io.jeyong.test.case2.entity.Product; 9 | import io.jeyong.test.case2.repository.OrderRepository; 10 | import io.jeyong.test.case2.repository.ProductRepository; 11 | import io.jeyong.test.case3.entity.Member; 12 | import io.jeyong.test.case3.entity.Team; 13 | import io.jeyong.test.case3.repository.MemberRepository; 14 | import io.jeyong.test.case3.repository.TeamRepository; 15 | import io.jeyong.test.case4.entity.Address; 16 | import io.jeyong.test.case4.entity.Person; 17 | import io.jeyong.test.case4.repository.AddressRepository; 18 | import io.jeyong.test.case4.repository.PersonRepository; 19 | import io.jeyong.test.case5.entity.Course; 20 | import io.jeyong.test.case5.entity.Student; 21 | import io.jeyong.test.case5.repository.CourseRepository; 22 | import io.jeyong.test.case5.repository.StudentRepository; 23 | import java.util.List; 24 | import lombok.RequiredArgsConstructor; 25 | import org.springframework.boot.context.event.ApplicationReadyEvent; 26 | import org.springframework.context.event.EventListener; 27 | import org.springframework.stereotype.Component; 28 | import org.springframework.transaction.annotation.Transactional; 29 | 30 | @Component 31 | @RequiredArgsConstructor 32 | public class InitData { 33 | 34 | private final AuthorRepository authorRepository; 35 | private final BookRepository bookRepository; 36 | private final OrderRepository orderRepository; 37 | private final ProductRepository productRepository; 38 | private final TeamRepository teamRepository; 39 | private final MemberRepository memberRepository; 40 | private final PersonRepository personRepository; 41 | private final AddressRepository addressRepository; 42 | private final CourseRepository courseRepository; 43 | private final StudentRepository studentRepository; 44 | 45 | @EventListener(ApplicationReadyEvent.class) 46 | @Transactional 47 | public void initData() { 48 | initCase1(); 49 | initCase2(); 50 | initCase3(); 51 | initCase4(); 52 | initCase5(); 53 | } 54 | 55 | private void initCase1() { 56 | Author author1 = new Author(); 57 | author1.setName("Author 1"); 58 | 59 | Author author2 = new Author(); 60 | author2.setName("Author 2"); 61 | 62 | authorRepository.save(author1); 63 | authorRepository.save(author2); 64 | 65 | Book book1 = new Book(); 66 | book1.setTitle("Book 1"); 67 | book1.setAuthor(author1); 68 | 69 | Book book2 = new Book(); 70 | book2.setTitle("Book 2"); 71 | book2.setAuthor(author1); 72 | 73 | Book book3 = new Book(); 74 | book3.setTitle("Book 3"); 75 | book3.setAuthor(author2); 76 | 77 | bookRepository.save(book1); 78 | bookRepository.save(book2); 79 | bookRepository.save(book3); 80 | } 81 | 82 | private void initCase2() { 83 | Order order1 = new Order(); 84 | order1.setOrderNumber("Order 1"); 85 | 86 | Order order2 = new Order(); 87 | order2.setOrderNumber("Order 2"); 88 | 89 | Order order3 = new Order(); 90 | order3.setOrderNumber("Order 3"); 91 | 92 | orderRepository.save(order1); 93 | orderRepository.save(order2); 94 | orderRepository.save(order3); 95 | 96 | Product product1 = new Product(); 97 | product1.setName("Product 1"); 98 | product1.setPrice(100.0); 99 | product1.setOrder(order1); 100 | 101 | Product product2 = new Product(); 102 | product2.setName("Product 2"); 103 | product2.setPrice(200.0); 104 | product2.setOrder(order1); 105 | 106 | Product product3 = new Product(); 107 | product3.setName("Product 3"); 108 | product3.setPrice(300.0); 109 | product3.setOrder(order2); 110 | 111 | Product product4 = new Product(); 112 | product4.setName("Product 4"); 113 | product4.setPrice(150.0); 114 | product4.setOrder(order3); 115 | 116 | productRepository.saveAll(List.of(product1, product2, product3, product4)); 117 | } 118 | 119 | private void initCase3() { 120 | Team team1 = new Team(); 121 | team1.setName("Team 1"); 122 | 123 | Team team2 = new Team(); 124 | team2.setName("Team 2"); 125 | 126 | Team team3 = new Team(); 127 | team3.setName("Team 3"); 128 | 129 | teamRepository.save(team1); 130 | teamRepository.save(team2); 131 | teamRepository.save(team3); 132 | 133 | Member member1 = new Member(); 134 | member1.setName("Member 1"); 135 | member1.setTeam(team1); 136 | 137 | Member member2 = new Member(); 138 | member2.setName("Member 2"); 139 | member2.setTeam(team1); 140 | 141 | Member member3 = new Member(); 142 | member3.setName("Member 3"); 143 | member3.setTeam(team2); 144 | 145 | Member member4 = new Member(); 146 | member4.setName("Member 4"); 147 | member4.setTeam(team3); 148 | 149 | memberRepository.saveAll(List.of(member1, member2, member3, member4)); 150 | } 151 | 152 | private void initCase4() { 153 | Address address1 = new Address(); 154 | address1.setStreet("123 Main St"); 155 | address1.setCity("City A"); 156 | 157 | Address address2 = new Address(); 158 | address2.setStreet("456 Elm St"); 159 | address2.setCity("City B"); 160 | 161 | Address address3 = new Address(); 162 | address3.setStreet("789 Oak St"); 163 | address3.setCity("City C"); 164 | 165 | addressRepository.saveAll(List.of(address1, address2, address3)); 166 | 167 | Person person1 = new Person(); 168 | person1.setName("Person 1"); 169 | person1.setAddress(address1); 170 | 171 | Person person2 = new Person(); 172 | person2.setName("Person 2"); 173 | person2.setAddress(address2); 174 | 175 | Person person3 = new Person(); 176 | person3.setName("Person 3"); 177 | person3.setAddress(address3); 178 | 179 | personRepository.saveAll(List.of(person1, person2, person3)); 180 | } 181 | 182 | private void initCase5() { 183 | Course course1 = new Course(); 184 | course1.setTitle("Course 1"); 185 | 186 | Course course2 = new Course(); 187 | course2.setTitle("Course 2"); 188 | 189 | Course course3 = new Course(); 190 | course3.setTitle("Course 3"); 191 | 192 | courseRepository.saveAll(List.of(course1, course2, course3)); 193 | 194 | Student student1 = new Student(); 195 | student1.setName("Student 1"); 196 | student1.getCourses().addAll(List.of(course1, course2)); 197 | 198 | Student student2 = new Student(); 199 | student2.setName("Student 2"); 200 | student2.getCourses().add(course2); 201 | 202 | Student student3 = new Student(); 203 | student3.setName("Student 3"); 204 | student3.getCourses().addAll(List.of(course2, course3)); 205 | 206 | studentRepository.saveAll(List.of(student1, student2, student3)); 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/TestApplication.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class TestApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(TestApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/controller/AuthorController.http: -------------------------------------------------------------------------------- 1 | ### 클래스 단위의 @Transactional 상황에서 감지하는 것을 검증 2 | GET http://localhost:8080/api/v1/authors 3 | 4 | ### 메서드 단위의 @Transactional 상황에서 감지하는 것을 검증 5 | GET http://localhost:8080/api/v2/authors 6 | 7 | ### OSIV를 이용한 지연 조회 상황에서 감지하는 것을 검증 8 | GET http://localhost:8080/api/v3/authors 9 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/controller/AuthorController.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case1.controller; 2 | 3 | import io.jeyong.test.case1.entity.Author; 4 | import io.jeyong.test.case1.service.AuthorServiceV1; 5 | import io.jeyong.test.case1.service.AuthorServiceV2; 6 | import io.jeyong.test.case1.service.AuthorServiceV3; 7 | import java.util.List; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | @RequestMapping("/api") 15 | @RequiredArgsConstructor 16 | public class AuthorController { 17 | 18 | private final AuthorServiceV1 authorServiceV1; 19 | private final AuthorServiceV2 authorServiceV2; 20 | private final AuthorServiceV3 authorServiceV3; 21 | 22 | // @formatter:off 23 | /** 24 | * Author과 Book는 일대다(1:N) 관계이며, 25 | * 모든 Author을 조회한 후 각 Author에 대해 별도의 쿼리로 Book을 조회 26 | * 클래스 단위의 @Transactional 상황에서 감지하는 것을 검증 27 | */ 28 | // @formatter:on 29 | @GetMapping("/v1/authors") 30 | public List getAuthorsV1() { 31 | return authorServiceV1.findAllAuthors(); 32 | } 33 | 34 | // @formatter:off 35 | /** 36 | * Author과 Book는 일대다(1:N) 관계이며, 37 | * 모든 Author을 조회한 후 각 Author에 대해 별도의 쿼리로 Book을 조회 38 | * 메서드 단위의 @Transactional 상황에서 감지하는 것을 검증 39 | */ 40 | // @formatter:on 41 | @GetMapping("/v2/authors") 42 | public List getAuthorsV2() { 43 | return authorServiceV2.findAllAuthors(); 44 | } 45 | 46 | // @formatter:off 47 | /** 48 | * Author과 Book는 일대다(1:N) 관계이며, 49 | * 모든 Author을 조회한 후 각 Author에 대해 별도의 쿼리로 Book을 조회 50 | * OSIV를 이용한 지연 조회 상황에서 감지하는 것을 검증 51 | */ 52 | // @formatter:on 53 | @GetMapping("/v3/authors") 54 | public List getAuthorsV3() { 55 | List allAuthors = authorServiceV3.findAllAuthors(); 56 | allAuthors.forEach(author -> author.getBooks().size()); // N+1 문제 발생 가능 57 | return allAuthors; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/entity/Author.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case1.entity; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.FetchType; 5 | import jakarta.persistence.GeneratedValue; 6 | import jakarta.persistence.GenerationType; 7 | import jakarta.persistence.Id; 8 | import jakarta.persistence.OneToMany; 9 | import java.util.List; 10 | import lombok.Getter; 11 | import lombok.NoArgsConstructor; 12 | import lombok.Setter; 13 | 14 | @Entity 15 | @Getter 16 | @Setter 17 | @NoArgsConstructor 18 | public class Author { 19 | 20 | @Id 21 | @GeneratedValue(strategy = GenerationType.IDENTITY) 22 | private Long id; 23 | 24 | private String name; 25 | 26 | @OneToMany(mappedBy = "author", fetch = FetchType.LAZY) 27 | private List books; 28 | } 29 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/entity/Book.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case1.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.FetchType; 6 | import jakarta.persistence.GeneratedValue; 7 | import jakarta.persistence.GenerationType; 8 | import jakarta.persistence.Id; 9 | import jakarta.persistence.JoinColumn; 10 | import jakarta.persistence.ManyToOne; 11 | import lombok.Getter; 12 | import lombok.NoArgsConstructor; 13 | import lombok.Setter; 14 | 15 | @Entity 16 | @Getter 17 | @Setter 18 | @NoArgsConstructor 19 | public class Book { 20 | 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private Long id; 24 | 25 | private String title; 26 | 27 | @JsonIgnore 28 | @ManyToOne(fetch = FetchType.LAZY) 29 | @JoinColumn(name = "author_id") 30 | private Author author; 31 | } 32 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/repository/AuthorRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case1.repository; 2 | 3 | import io.jeyong.test.case1.entity.Author; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface AuthorRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/repository/BookRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case1.repository; 2 | 3 | import io.jeyong.test.case1.entity.Book; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface BookRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/service/AuthorServiceV1.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case1.service; 2 | 3 | import io.jeyong.test.case1.entity.Author; 4 | import io.jeyong.test.case1.repository.AuthorRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @Transactional 12 | @RequiredArgsConstructor 13 | public class AuthorServiceV1 { 14 | 15 | private final AuthorRepository authorRepository; 16 | 17 | public List findAllAuthors() { 18 | List authors = authorRepository.findAll(); 19 | authors.forEach(author -> author.getBooks().size()); // N+1 문제 발생 가능 20 | return authors; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/service/AuthorServiceV2.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case1.service; 2 | 3 | import io.jeyong.test.case1.entity.Author; 4 | import io.jeyong.test.case1.repository.AuthorRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class AuthorServiceV2 { 13 | 14 | private final AuthorRepository authorRepository; 15 | 16 | @Transactional 17 | public List findAllAuthors() { 18 | List authors = authorRepository.findAll(); 19 | authors.forEach(author -> author.getBooks().size()); // N+1 문제 발생 가능 20 | return authors; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case1/service/AuthorServiceV3.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case1.service; 2 | 3 | import io.jeyong.test.case1.entity.Author; 4 | import io.jeyong.test.case1.repository.AuthorRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class AuthorServiceV3 { 13 | 14 | private final AuthorRepository authorRepository; 15 | 16 | @Transactional 17 | public List findAllAuthors() { 18 | return authorRepository.findAll(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case2/controller/ProductController.http: -------------------------------------------------------------------------------- 1 | ### N:1 관계에서 다(N)를 조회하는 상황에서 감지하는 것을 검증 2 | GET http://localhost:8080/api/products 3 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case2/controller/ProductController.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case2.controller; 2 | 3 | import io.jeyong.test.case2.entity.Product; 4 | import io.jeyong.test.case2.service.ProductService; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("/api/products") 13 | @RequiredArgsConstructor 14 | public class ProductController { 15 | 16 | private final ProductService productService; 17 | 18 | /** 19 | * @formatter:off 20 | * Product와 Order는 다대일(N:1) 관계이며, 21 | * 모든 Product를 조회한 후 각 Product에 대해 별도의 쿼리로 Order를 조회 22 | * N:1 관계에서 다(N)를 조회하는 상황에서 감지하는 것을 검증 23 | * @formatter:on 24 | */ 25 | @GetMapping 26 | public List getAllProducts() { 27 | return productService.findAllProducts(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case2/entity/Order.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case2.entity; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.GeneratedValue; 5 | import jakarta.persistence.GenerationType; 6 | import jakarta.persistence.Id; 7 | import jakarta.persistence.Table; 8 | import lombok.Getter; 9 | import lombok.NoArgsConstructor; 10 | import lombok.Setter; 11 | 12 | @Entity 13 | @Getter 14 | @Setter 15 | @NoArgsConstructor 16 | @Table(name = "`order`") 17 | public class Order { 18 | 19 | @Id 20 | @GeneratedValue(strategy = GenerationType.IDENTITY) 21 | private Long id; 22 | 23 | private String orderNumber; 24 | } 25 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case2/entity/Product.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case2.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.FetchType; 6 | import jakarta.persistence.GeneratedValue; 7 | import jakarta.persistence.GenerationType; 8 | import jakarta.persistence.Id; 9 | import jakarta.persistence.JoinColumn; 10 | import jakarta.persistence.ManyToOne; 11 | import lombok.Getter; 12 | import lombok.NoArgsConstructor; 13 | import lombok.Setter; 14 | 15 | @Entity 16 | @Getter 17 | @Setter 18 | @NoArgsConstructor 19 | public class Product { 20 | 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private Long id; 24 | 25 | private String name; 26 | 27 | private Double price; 28 | 29 | @ManyToOne(fetch = FetchType.LAZY) 30 | @JoinColumn(name = "order_id") 31 | @JsonIgnore 32 | private Order order; 33 | } 34 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case2/repository/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case2.repository; 2 | 3 | import io.jeyong.test.case2.entity.Order; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface OrderRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case2/repository/ProductRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case2.repository; 2 | 3 | import io.jeyong.test.case2.entity.Product; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface ProductRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case2/service/ProductService.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case2.service; 2 | 3 | import io.jeyong.test.case2.entity.Product; 4 | import io.jeyong.test.case2.repository.ProductRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class ProductService { 13 | 14 | private final ProductRepository productRepository; 15 | 16 | @Transactional 17 | public List findAllProducts() { 18 | List products = productRepository.findAll(); 19 | products.forEach(product -> product.getOrder().getOrderNumber()); // N+1 문제 발생 20 | return products; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case3/controller/TeamController.http: -------------------------------------------------------------------------------- 1 | ### @BatchSize 상황에서 감지하지 않는 것을 검증 2 | GET http://localhost:8080/api/teams 3 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case3/controller/TeamController.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case3.controller; 2 | 3 | import io.jeyong.test.case3.entity.Team; 4 | import io.jeyong.test.case3.service.TeamService; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("/api/teams") 13 | @RequiredArgsConstructor 14 | public class TeamController { 15 | 16 | private final TeamService teamService; 17 | 18 | // @formatter:off 19 | /** 20 | * Team과 Member는 일대다(1:N) 관계이며, 21 | * 모든 Team을 조회한 후 각 Team에 대해 별도의 쿼리로 Member를 조회 22 | * @BatchSize 상황에서 감지하지 않는 것을 검증 23 | */ 24 | // @formatter:on 25 | @GetMapping 26 | public List getAllTeams() { 27 | return teamService.findAllTeams(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case3/entity/Member.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case3.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.FetchType; 6 | import jakarta.persistence.GeneratedValue; 7 | import jakarta.persistence.GenerationType; 8 | import jakarta.persistence.Id; 9 | import jakarta.persistence.JoinColumn; 10 | import jakarta.persistence.ManyToOne; 11 | import lombok.Getter; 12 | import lombok.NoArgsConstructor; 13 | import lombok.Setter; 14 | 15 | @Entity 16 | @Getter 17 | @Setter 18 | @NoArgsConstructor 19 | public class Member { 20 | 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private Long id; 24 | 25 | private String name; 26 | 27 | @JsonIgnore 28 | @ManyToOne(fetch = FetchType.LAZY) 29 | @JoinColumn(name = "team_id") 30 | private Team team; 31 | } 32 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case3/entity/Team.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case3.entity; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.GeneratedValue; 5 | import jakarta.persistence.GenerationType; 6 | import jakarta.persistence.Id; 7 | import jakarta.persistence.OneToMany; 8 | import jakarta.persistence.Table; 9 | import java.util.List; 10 | import lombok.Getter; 11 | import lombok.NoArgsConstructor; 12 | import lombok.Setter; 13 | import org.hibernate.annotations.BatchSize; 14 | 15 | @Entity 16 | @Getter 17 | @Setter 18 | @NoArgsConstructor 19 | @Table(name = "team") 20 | public class Team { 21 | 22 | @Id 23 | @GeneratedValue(strategy = GenerationType.IDENTITY) 24 | private Long id; 25 | 26 | private String name; 27 | 28 | @OneToMany(mappedBy = "team") 29 | @BatchSize(size = 2) // BatchSize 설정 30 | private List members; 31 | } 32 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case3/repository/MemberRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case3.repository; 2 | 3 | import io.jeyong.test.case3.entity.Member; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface MemberRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case3/repository/TeamRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case3.repository; 2 | 3 | import io.jeyong.test.case3.entity.Team; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface TeamRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case3/service/TeamService.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case3.service; 2 | 3 | import io.jeyong.test.case3.entity.Team; 4 | import io.jeyong.test.case3.repository.TeamRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class TeamService { 13 | 14 | private final TeamRepository teamRepository; 15 | 16 | @Transactional 17 | public List findAllTeams() { 18 | List teams = teamRepository.findAll(); 19 | teams.forEach(team -> team.getMembers().size()); // N+1 문제 발생 20 | return teams; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/controller/AddressController.http: -------------------------------------------------------------------------------- 1 | ### 1:1 관계에서 일(1)을 즉시로딩으로 조회하는 상황에서 감지하는 것을 검증 2 | GET http://localhost:8080/api/addresses 3 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/controller/AddressController.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case4.controller; 2 | 3 | import io.jeyong.test.case4.entity.Address; 4 | import io.jeyong.test.case4.service.AddressService; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("/api/addresses") 13 | @RequiredArgsConstructor 14 | public class AddressController { 15 | 16 | private final AddressService addressService; 17 | 18 | // @formatter:off 19 | /** 20 | * Address와 Person은 일대일(1:1) 관계 21 | * 모든 Address을 조회한 후 각 Address에 대해 즉시로딩으로 Person를 조회 22 | * 1:1 관계에서 연관관계의 주인이 아닌 일(1)을 조회하는 상황에서 감지하는 것을 검증 23 | */ 24 | // @formatter:on 25 | @GetMapping 26 | public List
getAllAddresses() { 27 | return addressService.findAllAddresses(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/controller/PersonController.http: -------------------------------------------------------------------------------- 1 | ### 1:1 관계에서 일(1)을 조회하는 상황에서 감지하는 것을 검증 2 | GET http://localhost:8080/api/persons 3 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/controller/PersonController.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case4.controller; 2 | 3 | import io.jeyong.test.case4.entity.Person; 4 | import io.jeyong.test.case4.service.PersonService; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("/api/persons") 13 | @RequiredArgsConstructor 14 | public class PersonController { 15 | 16 | private final PersonService personService; 17 | 18 | // @formatter:off 19 | /** 20 | * Person과 Address는 일대일(1:1) 관계이며, 21 | * 모든 Person을 조회한 후 각 Person에 대해 별도의 쿼리로 Address를 조회 22 | * 1:1 관계에서 연관관계의 주인인 일(1)을 조회하는 상황에서 감지하는 것을 검증 23 | */ 24 | // @formatter:on 25 | @GetMapping 26 | public List getAllPersons() { 27 | return personService.findAllPersons(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/entity/Address.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case4.entity; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.FetchType; 5 | import jakarta.persistence.GeneratedValue; 6 | import jakarta.persistence.GenerationType; 7 | import jakarta.persistence.Id; 8 | import jakarta.persistence.OneToOne; 9 | import lombok.Getter; 10 | import lombok.NoArgsConstructor; 11 | import lombok.Setter; 12 | 13 | @Entity 14 | @Getter 15 | @Setter 16 | @NoArgsConstructor 17 | public class Address { 18 | 19 | @Id 20 | @GeneratedValue(strategy = GenerationType.IDENTITY) 21 | private Long id; 22 | 23 | private String street; 24 | private String city; 25 | 26 | @OneToOne(mappedBy = "address", fetch = FetchType.LAZY, optional = false) 27 | private Person person; 28 | } 29 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/entity/Person.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case4.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.FetchType; 6 | import jakarta.persistence.GeneratedValue; 7 | import jakarta.persistence.GenerationType; 8 | import jakarta.persistence.Id; 9 | import jakarta.persistence.OneToOne; 10 | import jakarta.persistence.JoinColumn; 11 | import lombok.Getter; 12 | import lombok.NoArgsConstructor; 13 | import lombok.Setter; 14 | 15 | @Entity 16 | @Getter 17 | @Setter 18 | @NoArgsConstructor 19 | public class Person { 20 | 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private Long id; 24 | 25 | private String name; 26 | 27 | @JsonIgnore 28 | @OneToOne(fetch = FetchType.LAZY) 29 | @JoinColumn(name = "address_id") 30 | private Address address; 31 | } 32 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/repository/AddressRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case4.repository; 2 | 3 | import io.jeyong.test.case4.entity.Address; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface AddressRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/repository/PersonRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case4.repository; 2 | 3 | import io.jeyong.test.case4.entity.Person; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface PersonRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/service/AddressService.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case4.service; 2 | 3 | import io.jeyong.test.case4.entity.Address; 4 | import io.jeyong.test.case4.repository.AddressRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class AddressService { 13 | 14 | private final AddressRepository addressRepository; 15 | 16 | @Transactional 17 | public List
findAllAddresses() { 18 | return addressRepository.findAll(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case4/service/PersonService.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case4.service; 2 | 3 | import io.jeyong.test.case4.entity.Person; 4 | import io.jeyong.test.case4.repository.PersonRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class PersonService { 13 | 14 | private final PersonRepository personRepository; 15 | 16 | @Transactional 17 | public List findAllPersons() { 18 | List persons = personRepository.findAll(); 19 | persons.forEach(person -> person.getAddress().getCity()); // N+1 문제 발생 20 | return persons; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/controller/CourseController.http: -------------------------------------------------------------------------------- 1 | ### N:N 관계에서 연관관계의 주인이 아닌 다(N)를 조회하는 상황에서 감지하는 것을 검증 2 | GET http://localhost:8080/api/courses 3 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/controller/CourseController.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case5.controller; 2 | 3 | import io.jeyong.test.case5.entity.Course; 4 | import io.jeyong.test.case5.service.CourseService; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("/api/courses") 13 | @RequiredArgsConstructor 14 | public class CourseController { 15 | 16 | private final CourseService courseService; 17 | 18 | // @formatter:off 19 | /** 20 | * Course와 Student는 다대다(N:N) 관계 21 | * 모든 Course를 조회한 후 각 Course에 대해 별도의 쿼리로 Student를 조회 22 | * N:N 관계에서 연관관계의 주인이 아닌 다(N)를 조회하는 상황에서 감지하는 것을 검증 23 | */ 24 | // @formatter:on 25 | @GetMapping 26 | public List getAllCourses() { 27 | return courseService.findAllCourses(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/controller/StudentController.http: -------------------------------------------------------------------------------- 1 | ### N:N 관계에서 연관관계의 주인인 다(N)를 조회하는 상황에서 감지하는 것을 검증 2 | GET http://localhost:8080/api/students 3 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/controller/StudentController.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case5.controller; 2 | 3 | import io.jeyong.test.case5.entity.Student; 4 | import io.jeyong.test.case5.service.StudentService; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("/api/students") 13 | @RequiredArgsConstructor 14 | public class StudentController { 15 | 16 | private final StudentService studentService; 17 | 18 | // @formatter:off 19 | /** 20 | * Student와 Course는 다대다(N:N) 관계 21 | * 모든 Student을 조회한 후 각 Student에 대해 별도의 쿼리로 Course를 조회 22 | * N:N 관계에서 연관관계의 주인인 다(N)를 조회하는 상황에서 감지하는 것을 검증 23 | */ 24 | // @formatter:on 25 | @GetMapping 26 | public List getAllStudents() { 27 | return studentService.findAllStudents(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/entity/Course.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case5.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.FetchType; 6 | import jakarta.persistence.GeneratedValue; 7 | import jakarta.persistence.GenerationType; 8 | import jakarta.persistence.Id; 9 | import jakarta.persistence.ManyToMany; 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | import lombok.Getter; 13 | import lombok.NoArgsConstructor; 14 | import lombok.Setter; 15 | 16 | @Entity 17 | @Getter 18 | @Setter 19 | @NoArgsConstructor 20 | public class Course { 21 | 22 | @Id 23 | @GeneratedValue(strategy = GenerationType.IDENTITY) 24 | private Long id; 25 | 26 | private String title; 27 | 28 | @JsonIgnore 29 | @ManyToMany(mappedBy = "courses", fetch = FetchType.LAZY) 30 | private Set students = new HashSet<>(); 31 | } 32 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/entity/Student.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case5.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.FetchType; 6 | import jakarta.persistence.GeneratedValue; 7 | import jakarta.persistence.GenerationType; 8 | import jakarta.persistence.Id; 9 | import jakarta.persistence.JoinColumn; 10 | import jakarta.persistence.JoinTable; 11 | import jakarta.persistence.ManyToMany; 12 | import java.util.HashSet; 13 | import java.util.Set; 14 | import lombok.Getter; 15 | import lombok.NoArgsConstructor; 16 | import lombok.Setter; 17 | 18 | @Entity 19 | @Getter 20 | @Setter 21 | @NoArgsConstructor 22 | public class Student { 23 | 24 | @Id 25 | @GeneratedValue(strategy = GenerationType.IDENTITY) 26 | private Long id; 27 | 28 | private String name; 29 | 30 | @JsonIgnore 31 | @ManyToMany(fetch = FetchType.LAZY) 32 | @JoinTable( 33 | name = "student_course", 34 | joinColumns = @JoinColumn(name = "student_id"), 35 | inverseJoinColumns = @JoinColumn(name = "course_id") 36 | ) 37 | private Set courses = new HashSet<>(); 38 | } 39 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/repository/CourseRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case5.repository; 2 | 3 | import io.jeyong.test.case5.entity.Course; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface CourseRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/repository/StudentRepository.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case5.repository; 2 | 3 | import io.jeyong.test.case5.entity.Student; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface StudentRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/service/CourseService.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case5.service; 2 | 3 | import io.jeyong.test.case5.entity.Course; 4 | import io.jeyong.test.case5.repository.CourseRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class CourseService { 13 | 14 | private final CourseRepository courseRepository; 15 | 16 | @Transactional 17 | public List findAllCourses() { 18 | List courses = courseRepository.findAll(); 19 | courses.forEach(course -> course.getStudents().size()); // N+1 문제 발생 20 | return courses; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/src/main/java/io/jeyong/test/case5/service/StudentService.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.case5.service; 2 | 3 | import io.jeyong.test.case5.entity.Student; 4 | import io.jeyong.test.case5.repository.StudentRepository; 5 | import java.util.List; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class StudentService { 13 | 14 | private final StudentRepository studentRepository; 15 | 16 | @Transactional 17 | public List findAllStudents() { 18 | List students = studentRepository.findAll(); 19 | students.forEach(student -> student.getCourses().size()); // N+1 문제 발생 20 | return students; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # spring.application.name=test 2 | 3 | # spring.datasource.driver-class-name=org.h2.Driver 4 | # spring.datasource.url=jdbc:h2:mem:test 5 | # spring.datasource.username=sa 6 | # spring.datasource.password= 7 | # spring.datasource.hikari.auto-commit=false 8 | 9 | # spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop 10 | # spring.jpa.properties.hibernate.detector.enabled=true 11 | # spring.jpa.properties.hibernate.detector.threshold=2 12 | # spring.jpa.properties.hibernate.detector.exclude[0]=select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=? 13 | # spring.jpa.properties.hibernate.detector.exclude[1]=select o1_0.id,o1_0.order_number from "order" o1_0 where o1_0.id=? 14 | # spring.jpa.properties.hibernate.detector.level=warn 15 | # spring.jpa.open-in-view=false 16 | 17 | # logging.level.org.hibernate.SQL=debug 18 | -------------------------------------------------------------------------------- /test/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: test 4 | 5 | datasource: 6 | driver-class-name: org.h2.Driver 7 | url: jdbc:h2:mem:test 8 | username: sa 9 | password: 10 | # hikari: 11 | # auto-commit: false 12 | 13 | jpa: 14 | properties: 15 | hibernate: 16 | hbm2ddl.auto: create-drop 17 | detector: 18 | enabled: true 19 | threshold: 2 20 | exclude: 21 | # - select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=? 22 | # - select o1_0.id,o1_0.order_number from "order" o1_0 where o1_0.id=? 23 | level: warn 24 | # open-in-view: false 25 | 26 | logging: 27 | level: 28 | org: 29 | hibernate: 30 | SQL: debug 31 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case1/controller/AuthorControllerTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case1.controller; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=warn" 26 | }) 27 | class AuthorControllerTest { 28 | 29 | @LocalServerPort 30 | private int port; 31 | 32 | @Autowired 33 | private TestRestTemplate restTemplate; 34 | 35 | @Test 36 | @DisplayName("클래스 단위의 @Transactional 상황에서 감지한다.") 37 | void testGetAuthorsV1(CapturedOutput output) { 38 | String url = "http://localhost:" + port + "/api/v1/authors"; 39 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 40 | 41 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 42 | assertThat(output).contains("N+1 query detected"); 43 | } 44 | 45 | @Test 46 | @DisplayName("메서드 단위의 @Transactional 상황에서 감지한다.") 47 | void testGetAuthorsV2(CapturedOutput output) { 48 | String url = "http://localhost:" + port + "/api/v2/authors"; 49 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 50 | 51 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 52 | assertThat(output).contains("N+1 query detected"); 53 | } 54 | 55 | @Test 56 | @DisplayName("OSIV를 이용한 지연 조회 상황에서 감지한다.") 57 | void testGetAuthorsV3(CapturedOutput output) { 58 | String url = "http://localhost:" + port + "/api/v3/authors"; 59 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 60 | 61 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 62 | assertThat(output).contains("N+1 query detected"); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case1/service/AuthorServiceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case1.service; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | 5 | import io.jeyong.test.case1.service.AuthorServiceV1; 6 | import io.jeyong.test.case1.service.AuthorServiceV2; 7 | import io.jeyong.test.case1.service.AuthorServiceV3; 8 | import org.junit.jupiter.api.DisplayName; 9 | import org.junit.jupiter.api.Test; 10 | import org.junit.jupiter.api.extension.ExtendWith; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.boot.test.system.CapturedOutput; 14 | import org.springframework.boot.test.system.OutputCaptureExtension; 15 | 16 | @ExtendWith(OutputCaptureExtension.class) 17 | @SpringBootTest( 18 | properties = { 19 | "spring.jpa.properties.hibernate.detector.enabled=true", 20 | "spring.jpa.properties.hibernate.detector.threshold=2", 21 | "spring.jpa.properties.hibernate.detector.exclude=", 22 | "spring.jpa.properties.hibernate.detector.level=warn" 23 | }) 24 | public class AuthorServiceTest { 25 | 26 | @Autowired 27 | private AuthorServiceV1 authorServiceV1; 28 | 29 | @Autowired 30 | private AuthorServiceV2 authorServiceV2; 31 | 32 | @Autowired 33 | private AuthorServiceV3 authorServiceV3; 34 | 35 | @Test 36 | @DisplayName("클래스 단위의 @Transactional 상황에서 감지한다.") 37 | void testFindAllAuthorsV1(CapturedOutput output) { 38 | authorServiceV1.findAllAuthors(); 39 | 40 | assertThat(output).contains("N+1 query detected"); 41 | } 42 | 43 | @Test 44 | @DisplayName("메서드 단위의 @Transactional 상황에서 감지한다.") 45 | void testFindAllAuthorsV2(CapturedOutput output) { 46 | authorServiceV2.findAllAuthors(); 47 | 48 | assertThat(output).contains("N+1 query detected"); 49 | } 50 | 51 | @Test 52 | @DisplayName("OSIV를 이용한 지연 조회 상황에서 감지한다.") 53 | void testFindAllAuthorsV3(CapturedOutput output) { 54 | authorServiceV3.findAllAuthors(); 55 | 56 | assertThat(output).doesNotContain("N+1 query detected"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case2/controller/ProductControllerTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case2.controller; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=warn" 26 | }) 27 | class ProductControllerTest { 28 | 29 | @LocalServerPort 30 | private int port; 31 | 32 | @Autowired 33 | private TestRestTemplate restTemplate; 34 | 35 | @Test 36 | @DisplayName("N:1 관계에서 다(N)를 조회하는 상황에서 감지한다.") 37 | void testGetProducts(CapturedOutput output) { 38 | String url = "http://localhost:" + port + "/api/products"; 39 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 40 | 41 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 42 | assertThat(output).contains("N+1 query detected"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case2/service/ProductServiceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case2.service; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | 5 | import io.jeyong.test.case2.service.ProductService; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.system.CapturedOutput; 12 | import org.springframework.boot.test.system.OutputCaptureExtension; 13 | 14 | @ExtendWith(OutputCaptureExtension.class) 15 | @SpringBootTest( 16 | properties = { 17 | "spring.jpa.properties.hibernate.detector.enabled=true", 18 | "spring.jpa.properties.hibernate.detector.threshold=2", 19 | "spring.jpa.properties.hibernate.detector.exclude=", 20 | "spring.jpa.properties.hibernate.detector.level=warn" 21 | }) 22 | public class ProductServiceTest { 23 | 24 | @Autowired 25 | private ProductService productService; 26 | 27 | @Test 28 | @DisplayName("다(N)를 조회하는 상황에서 감지한다.") 29 | void testFindAllProducts(CapturedOutput output) { 30 | productService.findAllProducts(); 31 | 32 | assertThat(output).contains("N+1 query detected"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case3/controller/TeamControllerTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case3.controller; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=warn" 26 | }) 27 | class TeamControllerTest { 28 | 29 | @LocalServerPort 30 | private int port; 31 | 32 | @Autowired 33 | private TestRestTemplate restTemplate; 34 | 35 | @Test 36 | @DisplayName("@BatchSize 상황에서 감지하지 않는다.") 37 | void testGetAllTeams(CapturedOutput output) { 38 | String url = "http://localhost:" + port + "/api/teams"; 39 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 40 | 41 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 42 | assertThat(output).doesNotContain("N+1 query detected"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case3/service/TeamServiceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case3.service; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | 5 | import io.jeyong.test.case3.service.TeamService; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.system.CapturedOutput; 12 | import org.springframework.boot.test.system.OutputCaptureExtension; 13 | 14 | @ExtendWith(OutputCaptureExtension.class) 15 | @SpringBootTest( 16 | properties = { 17 | "spring.jpa.properties.hibernate.detector.enabled=true", 18 | "spring.jpa.properties.hibernate.detector.threshold=2", 19 | "spring.jpa.properties.hibernate.detector.exclude=", 20 | "spring.jpa.properties.hibernate.detector.level=warn" 21 | }) 22 | public class TeamServiceTest { 23 | 24 | @Autowired 25 | private TeamService teamService; 26 | 27 | @Test 28 | @DisplayName("@BatchSize 상황에서 감지하지 않는다.") 29 | void testFindAllTeams(CapturedOutput output) { 30 | teamService.findAllTeams(); 31 | 32 | assertThat(output).doesNotContain("N+1 query detected"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case4/controller/AddressControllerTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case4.controller; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=warn" 26 | }) 27 | class AddressControllerTest { 28 | 29 | @LocalServerPort 30 | private int port; 31 | 32 | @Autowired 33 | private TestRestTemplate restTemplate; 34 | 35 | @Test 36 | @DisplayName("1:1 관계에서 연관관계의 주인이 아닌 일(1)을 조회하는 상황에서 감지한다.") 37 | void testGetAddresses(CapturedOutput output) { 38 | String url = "http://localhost:" + port + "/api/addresses"; 39 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 40 | 41 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 42 | assertThat(output).contains("N+1 query detected"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case4/controller/PersonControllerTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case4.controller; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=warn" 26 | }) 27 | class PersonControllerTest { 28 | 29 | @LocalServerPort 30 | private int port; 31 | 32 | @Autowired 33 | private TestRestTemplate restTemplate; 34 | 35 | @Test 36 | @DisplayName("1:1 관계에서 연관관계의 주인인 일(1)을 조회하는 상황에서 감지한다.") 37 | void testGetPersons(CapturedOutput output) { 38 | String url = "http://localhost:" + port + "/api/persons"; 39 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 40 | 41 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 42 | assertThat(output).contains("N+1 query detected"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case4/service/AddressServiceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case4.service; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | 5 | import io.jeyong.test.case4.service.AddressService; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.system.CapturedOutput; 12 | import org.springframework.boot.test.system.OutputCaptureExtension; 13 | 14 | @ExtendWith(OutputCaptureExtension.class) 15 | @SpringBootTest( 16 | properties = { 17 | "spring.jpa.properties.hibernate.detector.enabled=true", 18 | "spring.jpa.properties.hibernate.detector.threshold=2", 19 | "spring.jpa.properties.hibernate.detector.exclude=", 20 | "spring.jpa.properties.hibernate.detector.level=warn" 21 | }) 22 | public class AddressServiceTest { 23 | 24 | @Autowired 25 | private AddressService addressService; 26 | 27 | @Test 28 | @DisplayName("1:1 관계에서 연관관계의 주인이 아닌 일(1)을 조회하는 상황에서 감지한다.") 29 | void testFindAllAddresses(CapturedOutput output) { 30 | addressService.findAllAddresses(); 31 | 32 | assertThat(output).contains("N+1 query detected"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case4/service/PersonServiceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case4.service; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | 5 | import io.jeyong.test.case4.service.PersonService; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.system.CapturedOutput; 12 | import org.springframework.boot.test.system.OutputCaptureExtension; 13 | 14 | @ExtendWith(OutputCaptureExtension.class) 15 | @SpringBootTest( 16 | properties = { 17 | "spring.jpa.properties.hibernate.detector.enabled=true", 18 | "spring.jpa.properties.hibernate.detector.threshold=2", 19 | "spring.jpa.properties.hibernate.detector.exclude=", 20 | "spring.jpa.properties.hibernate.detector.level=warn" 21 | }) 22 | public class PersonServiceTest { 23 | 24 | @Autowired 25 | private PersonService personService; 26 | 27 | @Test 28 | @DisplayName("1:1 관계에서 연관관계의 주인인 일(1)을 조회하는 상황에서 감지한다.") 29 | void testFindAllPersons(CapturedOutput output) { 30 | personService.findAllPersons(); 31 | 32 | assertThat(output).contains("N+1 query detected"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case5/controller/CourseControllerTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case5.controller; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=warn" 26 | }) 27 | class CourseControllerTest { 28 | 29 | @LocalServerPort 30 | private int port; 31 | 32 | @Autowired 33 | private TestRestTemplate restTemplate; 34 | 35 | @Test 36 | @DisplayName("N:N 관계에서 연관관계의 주인이 아닌 다(N)를 조회하는 상황에서 감지한다.") 37 | void testGetCourses(CapturedOutput output) { 38 | String url = "http://localhost:" + port + "/api/courses"; 39 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 40 | 41 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 42 | assertThat(output).contains("N+1 query detected"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case5/controller/StudentControllerTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case5.controller; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=warn" 26 | }) 27 | class StudentControllerTest { 28 | 29 | @LocalServerPort 30 | private int port; 31 | 32 | @Autowired 33 | private TestRestTemplate restTemplate; 34 | 35 | @Test 36 | @DisplayName("N:N 관계에서 연관관계의 주인인 다(N)를 조회하는 상황에서 감지한다.") 37 | void testGetStudents(CapturedOutput output) { 38 | String url = "http://localhost:" + port + "/api/students"; 39 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 40 | 41 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 42 | assertThat(output).contains("N+1 query detected"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case5/service/CourseServiceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case5.service; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | 5 | import io.jeyong.test.case5.service.CourseService; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.system.CapturedOutput; 12 | import org.springframework.boot.test.system.OutputCaptureExtension; 13 | 14 | @ExtendWith(OutputCaptureExtension.class) 15 | @SpringBootTest( 16 | properties = { 17 | "spring.jpa.properties.hibernate.detector.enabled=true", 18 | "spring.jpa.properties.hibernate.detector.threshold=2", 19 | "spring.jpa.properties.hibernate.detector.exclude=", 20 | "spring.jpa.properties.hibernate.detector.level=warn" 21 | }) 22 | public class CourseServiceTest { 23 | 24 | @Autowired 25 | private CourseService courseService; 26 | 27 | @Test 28 | @DisplayName("N:N 관계에서 연관관계의 주인이 아닌 다(N)를 조회하는 상황에서 감지한다.") 29 | void testFindAllCourses(CapturedOutput output) { 30 | courseService.findAllCourses(); 31 | 32 | assertThat(output).contains("N+1 query detected"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/case5/service/StudentServiceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.case5.service; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | 5 | import io.jeyong.test.case5.service.StudentService; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.system.CapturedOutput; 12 | import org.springframework.boot.test.system.OutputCaptureExtension; 13 | 14 | @ExtendWith(OutputCaptureExtension.class) 15 | @SpringBootTest( 16 | properties = { 17 | "spring.jpa.properties.hibernate.detector.enabled=true", 18 | "spring.jpa.properties.hibernate.detector.threshold=2", 19 | "spring.jpa.properties.hibernate.detector.exclude=", 20 | "spring.jpa.properties.hibernate.detector.level=warn" 21 | }) 22 | public class StudentServiceTest { 23 | 24 | @Autowired 25 | private StudentService studentService; 26 | 27 | @Test 28 | @DisplayName("N:N 관계에서 연관관계의 주인인 다(N)를 조회하는 상황에서 감지한다.") 29 | void testFindAllStudents(CapturedOutput output) { 30 | studentService.findAllStudents(); 31 | 32 | assertThat(output).contains("N+1 query detected"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/exclude/ExcludeQueryTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.exclude; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude[0]=select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?", 25 | "spring.jpa.properties.hibernate.detector.exclude[1]=select o1_0.id,o1_0.order_number from \"order\" o1_0 where o1_0.id=?", 26 | "spring.jpa.properties.hibernate.detector.level=warn", 27 | }) 28 | class ExcludeQueryTest { 29 | 30 | @LocalServerPort 31 | private int port; 32 | 33 | @Autowired 34 | private TestRestTemplate restTemplate; 35 | 36 | @Test 37 | @DisplayName("첫 번째로 제외된 쿼리는 감지하지 않는다.") 38 | void testFirstExcludedQuery(CapturedOutput output) { 39 | String url = "http://localhost:" + port + "/api/v1/authors"; 40 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 41 | 42 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 43 | assertThat(output).doesNotContain("N+1 query detected"); 44 | } 45 | 46 | @Test 47 | @DisplayName("두 번째로 제외된 쿼리는 감지하지 않는다.") 48 | void testSecondExcludedQuery(CapturedOutput output) { 49 | String url = "http://localhost:" + port + "/api/products"; 50 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 51 | 52 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 53 | assertThat(output).doesNotContain("N+1 query detected"); 54 | } 55 | 56 | @Test 57 | @DisplayName("제외되지 않은 쿼리는 감지한다.") 58 | void testNonExcludedQuery(CapturedOutput output) { 59 | String url = "http://localhost:" + port + "/api/addresses"; 60 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 61 | 62 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 63 | assertThat(output).contains("N+1 query detected"); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/level/LoggerLevelDebugTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.level; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=debug", 26 | "logging.level.io.jeyong=debug" 27 | }) 28 | class LoggerLevelDebugTest { 29 | 30 | @LocalServerPort 31 | private int port; 32 | 33 | @Autowired 34 | private TestRestTemplate restTemplate; 35 | 36 | @Test 37 | @DisplayName("DEBUG 레벨에서 로그가 출력된다.") 38 | void testDebugLogLevel(CapturedOutput output) { 39 | String url = "http://localhost:" + port + "/api/products"; 40 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 41 | 42 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 43 | assertThat(output).contains("N+1 query detected"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/level/LoggerLevelErrorTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.level; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=error", 26 | "logging.level.io.jeyong=error" 27 | }) 28 | class LoggerLevelErrorTest { 29 | 30 | @LocalServerPort 31 | private int port; 32 | 33 | @Autowired 34 | private TestRestTemplate restTemplate; 35 | 36 | @Test 37 | @DisplayName("ERROR 레벨에서 로그가 출력된다.") 38 | void testErrorLogLevel(CapturedOutput output) { 39 | String url = "http://localhost:" + port + "/api/products"; 40 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 41 | 42 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 43 | assertThat(output).contains("N+1 query detected"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/level/LoggerLevelInfoTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.level; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=info", 26 | "logging.level.io.jeyong=info" 27 | }) 28 | class LoggerLevelInfoTest { 29 | 30 | @LocalServerPort 31 | private int port; 32 | 33 | @Autowired 34 | private TestRestTemplate restTemplate; 35 | 36 | @Test 37 | @DisplayName("INFO 레벨에서 로그가 출력된다.") 38 | void testInfoLogLevel(CapturedOutput output) { 39 | String url = "http://localhost:" + port + "/api/products"; 40 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 41 | 42 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 43 | assertThat(output).contains("N+1 query detected"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/level/LoggerLevelTraceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.level; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=trace", 26 | "logging.level.io.jeyong=trace" 27 | }) 28 | class LoggerLevelTraceTest { 29 | 30 | @LocalServerPort 31 | private int port; 32 | 33 | @Autowired 34 | private TestRestTemplate restTemplate; 35 | 36 | @Test 37 | @DisplayName("TRACE 레벨에서 로그가 출력된다.") 38 | void testTraceLogLevel(CapturedOutput output) { 39 | String url = "http://localhost:" + port + "/api/products"; 40 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 41 | 42 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 43 | assertThat(output).contains("N+1 query detected"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/main/level/LoggerLevelWarnTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.main.level; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.system.CapturedOutput; 13 | import org.springframework.boot.test.system.OutputCaptureExtension; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.boot.test.web.server.LocalServerPort; 16 | import org.springframework.http.ResponseEntity; 17 | 18 | @ExtendWith(OutputCaptureExtension.class) 19 | @SpringBootTest( 20 | webEnvironment = RANDOM_PORT, 21 | properties = { 22 | "spring.jpa.properties.hibernate.detector.enabled=true", 23 | "spring.jpa.properties.hibernate.detector.threshold=2", 24 | "spring.jpa.properties.hibernate.detector.exclude=", 25 | "spring.jpa.properties.hibernate.detector.level=warn", 26 | "logging.level.io.jeyong=warn" 27 | }) 28 | class LoggerLevelWarnTest { 29 | 30 | @LocalServerPort 31 | private int port; 32 | 33 | @Autowired 34 | private TestRestTemplate restTemplate; 35 | 36 | @Test 37 | @DisplayName("WARN 레벨에서 로그가 출력된다.") 38 | void testWarnLogLevel(CapturedOutput output) { 39 | String url = "http://localhost:" + port + "/api/products"; 40 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 41 | 42 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 43 | assertThat(output).contains("N+1 query detected"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/annotation/AnnotationTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.annotation; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import io.jeyong.detector.annotation.NPlusOneTest; 6 | import io.jeyong.detector.config.NPlusOneDetectorProperties; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.slf4j.event.Level; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.test.context.TestPropertySource; 13 | import org.springframework.test.context.junit.jupiter.SpringExtension; 14 | 15 | @NPlusOneTest( 16 | threshold = 3, 17 | level = Level.DEBUG, 18 | exclude = { 19 | "annotationExcludeQuery1", 20 | "annotationExcludeQuery2" 21 | } 22 | ) 23 | @ExtendWith(SpringExtension.class) 24 | @TestPropertySource( 25 | properties = { 26 | "spring.jpa.properties.hibernate.detector.threshold=10", 27 | "spring.jpa.properties.hibernate.detector.level=warn", 28 | "spring.jpa.properties.hibernate.detector.exclude[0]=envExcludeQuery1", 29 | "spring.jpa.properties.hibernate.detector.exclude[1]=envExcludeQuery2" 30 | }) 31 | class AnnotationTest { 32 | 33 | @Autowired 34 | private NPlusOneDetectorProperties nPlusOneDetectorProperties; 35 | 36 | @Test 37 | @DisplayName("@NPlusOneTest에서 지정한 설정이 우선적으로 적용된다.") 38 | void testAnnotationConfiguration() { 39 | assertThat(nPlusOneDetectorProperties.getThreshold()).isEqualTo(3); 40 | assertThat(nPlusOneDetectorProperties.getLevel()).isEqualTo(Level.DEBUG); 41 | 42 | assertThat(nPlusOneDetectorProperties.getExclude()) 43 | .containsExactly( 44 | "annotationExcludeQuery1", 45 | "annotationExcludeQuery2" 46 | ); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/exclude/ExcludeQueryTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.exclude; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import io.jeyong.detector.annotation.NPlusOneTest; 7 | import java.util.List; 8 | import org.junit.jupiter.api.DisplayName; 9 | import org.junit.jupiter.api.Test; 10 | import org.junit.jupiter.api.extension.ExtendWith; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.boot.test.system.CapturedOutput; 14 | import org.springframework.boot.test.system.OutputCaptureExtension; 15 | import org.springframework.boot.test.web.client.TestRestTemplate; 16 | import org.springframework.boot.test.web.server.LocalServerPort; 17 | import org.springframework.http.ResponseEntity; 18 | 19 | @NPlusOneTest( 20 | exclude = { 21 | "select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?", 22 | "select o1_0.id,o1_0.order_number from \"order\" o1_0 where o1_0.id=?" 23 | }) 24 | @ExtendWith(OutputCaptureExtension.class) 25 | @SpringBootTest(webEnvironment = RANDOM_PORT) 26 | class ExcludeQueryTest { 27 | 28 | @LocalServerPort 29 | private int port; 30 | 31 | @Autowired 32 | private TestRestTemplate restTemplate; 33 | 34 | @Test 35 | @DisplayName("첫 번째로 제외된 쿼리는 감지하지 않는다.") 36 | void testFirstExcludedQuery(CapturedOutput output) { 37 | String url = "http://localhost:" + port + "/api/v1/authors"; 38 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 39 | 40 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 41 | assertThat(output).doesNotContain("N+1 query detected"); 42 | } 43 | 44 | @Test 45 | @DisplayName("두 번째로 제외된 쿼리는 감지하지 않는다.") 46 | void testSecondExcludedQuery(CapturedOutput output) { 47 | String url = "http://localhost:" + port + "/api/products"; 48 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 49 | 50 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 51 | assertThat(output).doesNotContain("N+1 query detected"); 52 | } 53 | 54 | @Test 55 | @DisplayName("제외되지 않은 쿼리는 감지한다.") 56 | void testNonExcludedQuery(CapturedOutput output) { 57 | String url = "http://localhost:" + port + "/api/addresses"; 58 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 59 | 60 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 61 | assertThat(output).contains("N+1 query detected"); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/mode/configuration/ExceptionModeConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.mode.configuration; 2 | 3 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 4 | 5 | import io.jeyong.detector.annotation.NPlusOneTest; 6 | import io.jeyong.detector.config.NPlusOneDetectorProperties; 7 | import io.jeyong.detector.context.ExceptionContext; 8 | import io.jeyong.detector.template.NPlusOneQueryCollector; 9 | import io.jeyong.detector.template.NPlusOneQueryTemplate; 10 | import org.junit.jupiter.api.DisplayName; 11 | import org.junit.jupiter.api.Test; 12 | import org.junit.jupiter.api.extension.ExtendWith; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.context.ApplicationContext; 15 | import org.springframework.test.context.junit.jupiter.SpringExtension; 16 | 17 | @NPlusOneTest(mode = NPlusOneTest.Mode.EXCEPTION) 18 | @ExtendWith(SpringExtension.class) 19 | public class ExceptionModeConfigurationTest { 20 | 21 | @Autowired 22 | private ApplicationContext applicationContext; 23 | 24 | @Autowired 25 | private NPlusOneDetectorProperties nPlusOneDetectorProperties; 26 | 27 | @Test 28 | @DisplayName("EXCEPTION 모드의 설정이 작동한다.") 29 | void testExceptionModeConfiguration() { 30 | assertThat(nPlusOneDetectorProperties.isEnabled()).isFalse(); 31 | 32 | NPlusOneQueryTemplate template = applicationContext.getBean(NPlusOneQueryTemplate.class); 33 | assertThat(template).isInstanceOf(NPlusOneQueryCollector.class); 34 | 35 | ExceptionContext exceptionContext = applicationContext.getBean(ExceptionContext.class); 36 | assertThat(exceptionContext).isNotNull(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/mode/configuration/LoggingModeConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.mode.configuration; 2 | 3 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 4 | 5 | import io.jeyong.detector.annotation.NPlusOneTest; 6 | import io.jeyong.detector.config.NPlusOneDetectorProperties; 7 | import io.jeyong.detector.template.NPlusOneQueryLogger; 8 | import io.jeyong.detector.template.NPlusOneQueryTemplate; 9 | import org.junit.jupiter.api.DisplayName; 10 | import org.junit.jupiter.api.Test; 11 | import org.junit.jupiter.api.extension.ExtendWith; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.context.ApplicationContext; 14 | import org.springframework.test.context.junit.jupiter.SpringExtension; 15 | 16 | @NPlusOneTest(mode = NPlusOneTest.Mode.LOGGING) 17 | @ExtendWith(SpringExtension.class) 18 | public class LoggingModeConfigurationTest { 19 | 20 | @Autowired 21 | private ApplicationContext applicationContext; 22 | 23 | @Autowired 24 | private NPlusOneDetectorProperties nPlusOneDetectorProperties; 25 | 26 | @Test 27 | @DisplayName("LOGGING 모드의 설정이 작동한다.") 28 | void testLoggingModeConfiguration() { 29 | assertThat(nPlusOneDetectorProperties.isEnabled()).isTrue(); 30 | 31 | NPlusOneQueryTemplate template = applicationContext.getBean(NPlusOneQueryTemplate.class); 32 | assertThat(template).isInstanceOf(NPlusOneQueryLogger.class); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/mode/integration/ExceptionModeIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.mode.integration; 2 | 3 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import io.jeyong.detector.annotation.NPlusOneTest; 7 | import io.jeyong.test.case2.service.ProductService; 8 | import io.jeyong.test.case4.service.AddressService; 9 | import io.jeyong.test.case4.service.PersonService; 10 | import java.util.List; 11 | import org.junit.jupiter.api.Disabled; 12 | import org.junit.jupiter.api.DisplayName; 13 | import org.junit.jupiter.api.Test; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.boot.test.context.SpringBootTest; 16 | import org.springframework.boot.test.web.client.TestRestTemplate; 17 | import org.springframework.boot.test.web.server.LocalServerPort; 18 | import org.springframework.http.ResponseEntity; 19 | 20 | @NPlusOneTest(mode = NPlusOneTest.Mode.EXCEPTION) 21 | @SpringBootTest(webEnvironment = RANDOM_PORT) 22 | class ExceptionModeIntegrationTest { 23 | 24 | @LocalServerPort 25 | private int port; 26 | 27 | @Autowired 28 | private TestRestTemplate restTemplate; 29 | 30 | @Autowired 31 | private ProductService productService; 32 | 33 | @Autowired 34 | private AddressService addressService; 35 | 36 | @Autowired 37 | private PersonService personService; 38 | 39 | @Disabled("BeforeEach 메서드에서 발생하는 예외는 테스트할 수 없다.") 40 | @Test 41 | @DisplayName("@SpringBootTest를 이용한 API를 호출하는 상황에서 EXCEPTION 모드가 동작한다.") 42 | void testExceptionModeInApiCall() { 43 | String url = "http://localhost:" + port + "/api/products"; 44 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 45 | 46 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 47 | } 48 | 49 | @Disabled("BeforeEach 메서드에서 발생하는 예외는 테스트할 수 없다.") 50 | @Test 51 | @DisplayName("@SpringBootTest를 이용한 Business Logic을 호출에서 상황에서 EXCEPTION 모드가 동작한다.") 52 | void testExceptionModeInBusinessLogicCall() { 53 | productService.findAllProducts(); 54 | } 55 | 56 | @Disabled("BeforeEach 메서드에서 발생하는 예외는 테스트할 수 없다.") 57 | @Test 58 | @DisplayName("@SpringBootTest를 이용한 여러번의 예외 발생 상황에서 EXCEPTION 모드가 동작한다.") 59 | void testExceptionModeInMultipleExceptions() { 60 | productService.findAllProducts(); 61 | addressService.findAllAddresses(); 62 | personService.findAllPersons(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/mode/integration/LoggingModeIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.mode.integration; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; 5 | 6 | import io.jeyong.detector.annotation.NPlusOneTest; 7 | import io.jeyong.test.case2.service.ProductService; 8 | import java.util.List; 9 | import org.junit.jupiter.api.DisplayName; 10 | import org.junit.jupiter.api.Test; 11 | import org.junit.jupiter.api.extension.ExtendWith; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.test.context.SpringBootTest; 14 | import org.springframework.boot.test.system.CapturedOutput; 15 | import org.springframework.boot.test.system.OutputCaptureExtension; 16 | import org.springframework.boot.test.web.client.TestRestTemplate; 17 | import org.springframework.boot.test.web.server.LocalServerPort; 18 | import org.springframework.http.ResponseEntity; 19 | 20 | @NPlusOneTest(mode = NPlusOneTest.Mode.LOGGING) 21 | @ExtendWith(OutputCaptureExtension.class) 22 | @SpringBootTest(webEnvironment = RANDOM_PORT) 23 | class LoggingModeIntegrationTest { 24 | 25 | @LocalServerPort 26 | private int port; 27 | 28 | @Autowired 29 | private TestRestTemplate restTemplate; 30 | 31 | @Autowired 32 | private ProductService productService; 33 | 34 | @Test 35 | @DisplayName("@SpringBootTest를 이용한 API를 호출하는 상황에서 LOGGING 모드가 동작한다.") 36 | void testLoggingModeInApiCall(CapturedOutput output) { 37 | String url = "http://localhost:" + port + "/api/products"; 38 | ResponseEntity response = restTemplate.getForEntity(url, List.class); 39 | 40 | assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); 41 | assertThat(output).contains("N+1 query detected"); 42 | } 43 | 44 | @Test 45 | @DisplayName("@SpringBootTest를 이용한 Business Logic을 호출에서 상황에서 LOGGING 모드가 동작한다.") 46 | void testLoggingModeInBusinessLogicCall(CapturedOutput output) { 47 | productService.findAllProducts(); 48 | 49 | assertThat(output).contains("N+1 query detected"); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/mode/unit/ExceptionModeUnitTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.mode.unit; 2 | 3 | import io.jeyong.detector.annotation.NPlusOneTest; 4 | import io.jeyong.test.case4.repository.AddressRepository; 5 | import io.jeyong.test.environment.test.mode.unit.config.TestInitDataConfig; 6 | import org.junit.jupiter.api.Disabled; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 11 | import org.springframework.context.annotation.Import; 12 | 13 | @NPlusOneTest(mode = NPlusOneTest.Mode.EXCEPTION) 14 | @DataJpaTest 15 | @Import(TestInitDataConfig.class) 16 | class ExceptionModeUnitTest { 17 | 18 | @Autowired 19 | private AddressRepository addressRepository; 20 | 21 | @Disabled("BeforeEach 메서드에서 발생하는 예외는 테스트할 수 없다.") 22 | @Test 23 | @DisplayName("@DataJpaTest를 이용한 Repository를 호출하는 상황에서 EXCEPTION 모드가 동작한다.") 24 | void testExceptionModeInRepositoryCall() { 25 | addressRepository.findAll(); // N+1 문제 발생 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/mode/unit/LoggingModeUnitTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.mode.unit; 2 | 3 | import io.jeyong.detector.annotation.NPlusOneTest; 4 | import io.jeyong.test.case4.repository.AddressRepository; 5 | import io.jeyong.test.environment.test.mode.unit.config.TestInitDataConfig; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 10 | import org.springframework.context.annotation.Import; 11 | 12 | @NPlusOneTest(mode = NPlusOneTest.Mode.LOGGING) 13 | @DataJpaTest(showSql = false) 14 | @Import(TestInitDataConfig.class) 15 | class LoggingModeUnitTest { 16 | 17 | @Autowired 18 | private AddressRepository addressRepository; 19 | 20 | @Test 21 | @DisplayName("@DataJpaTest를 이용한 Repository를 호출하는 상황에서 LOGGING 모드가 동작한다.") 22 | void testLoggingModeInRepositoryCall() { 23 | addressRepository.findAll(); // N+1 문제 발생 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/test/mode/unit/config/TestInitDataConfig.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.test.mode.unit.config; 2 | 3 | import io.jeyong.test.InitData; 4 | import io.jeyong.test.case1.repository.AuthorRepository; 5 | import io.jeyong.test.case1.repository.BookRepository; 6 | import io.jeyong.test.case2.repository.OrderRepository; 7 | import io.jeyong.test.case2.repository.ProductRepository; 8 | import io.jeyong.test.case3.repository.MemberRepository; 9 | import io.jeyong.test.case3.repository.TeamRepository; 10 | import io.jeyong.test.case4.repository.AddressRepository; 11 | import io.jeyong.test.case4.repository.PersonRepository; 12 | import io.jeyong.test.case5.repository.CourseRepository; 13 | import io.jeyong.test.case5.repository.StudentRepository; 14 | import org.springframework.boot.test.context.TestConfiguration; 15 | import org.springframework.context.annotation.Bean; 16 | 17 | @TestConfiguration 18 | public class TestInitDataConfig { 19 | 20 | @Bean 21 | public InitData initData( 22 | AuthorRepository authorRepository, 23 | BookRepository bookRepository, 24 | OrderRepository orderRepository, 25 | ProductRepository productRepository, 26 | TeamRepository teamRepository, 27 | MemberRepository memberRepository, 28 | PersonRepository personRepository, 29 | AddressRepository addressRepository, 30 | CourseRepository courseRepository, 31 | StudentRepository studentRepository 32 | ) { 33 | return new InitData( 34 | authorRepository, bookRepository, orderRepository, productRepository, 35 | teamRepository, memberRepository, personRepository, 36 | addressRepository, courseRepository, studentRepository); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/workbench/concurrency/ExceptionContextConcurrencyTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.workbench.concurrency; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import io.jeyong.detector.context.ExceptionContext; 6 | import io.jeyong.detector.exception.NPlusOneQueryException; 7 | import java.util.concurrent.CountDownLatch; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | import org.junit.jupiter.api.DisplayName; 11 | import org.junit.jupiter.api.Test; 12 | 13 | class ExceptionContextConcurrencyTest { 14 | 15 | @Test 16 | @DisplayName("ExceptionContext 동시성 테스트") 17 | void testSaveExceptionConcurrency() throws InterruptedException { 18 | // given 19 | ExceptionContext exceptionContext = new ExceptionContext(); 20 | int numberOfThreads = 10; 21 | ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); 22 | CountDownLatch countDownLatch = new CountDownLatch(numberOfThreads); 23 | 24 | // when 25 | for (int i = 0; i < numberOfThreads; i++) { 26 | int threadIndex = i; 27 | executorService.submit(() -> { 28 | try { 29 | NPlusOneQueryException exception = new NPlusOneQueryException("Exception-" + threadIndex); 30 | exceptionContext.saveException(exception); 31 | } catch (Exception e) { 32 | System.out.println(e.getMessage()); 33 | } finally { 34 | countDownLatch.countDown(); 35 | } 36 | }); 37 | } 38 | 39 | countDownLatch.await(); 40 | executorService.shutdown(); 41 | 42 | // then 43 | NPlusOneQueryException primaryException = exceptionContext.getContext().get(); 44 | assertThat(primaryException.getSuppressed()).hasSize(numberOfThreads - 1); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/workbench/performance/ExceptionContextPerformanceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.workbench.performance; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import io.jeyong.detector.exception.NPlusOneQueryException; 6 | import java.util.Optional; 7 | import java.util.concurrent.CountDownLatch; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.atomic.AtomicReference; 11 | import org.junit.jupiter.api.Disabled; 12 | import org.junit.jupiter.api.DisplayName; 13 | import org.junit.jupiter.api.Test; 14 | 15 | class ExceptionContextPerformanceTest { 16 | 17 | static class SyncExceptionContext { 18 | 19 | private NPlusOneQueryException primaryException; 20 | 21 | public synchronized void saveException(final NPlusOneQueryException nPlusOneQueryException) { 22 | if (primaryException != null) { 23 | primaryException.addSuppressed(nPlusOneQueryException); 24 | } else { 25 | primaryException = nPlusOneQueryException; 26 | } 27 | } 28 | 29 | public synchronized Optional getContext() { 30 | return Optional.ofNullable(primaryException); 31 | } 32 | 33 | public synchronized void clearContext() { 34 | primaryException = null; 35 | } 36 | } 37 | 38 | static class AtomicExceptionContext { 39 | 40 | private final AtomicReference primaryException = new AtomicReference<>(); 41 | 42 | public void saveException(final NPlusOneQueryException nPlusOneQueryException) { 43 | primaryException.updateAndGet(existingException -> { 44 | if (existingException != null) { 45 | existingException.addSuppressed(nPlusOneQueryException); 46 | return existingException; 47 | } else { 48 | return nPlusOneQueryException; 49 | } 50 | }); 51 | } 52 | 53 | public Optional getContext() { 54 | return Optional.ofNullable(primaryException.get()); 55 | } 56 | 57 | public void clearContext() { 58 | primaryException.set(null); 59 | } 60 | } 61 | 62 | private static final int NUM_ITERATIONS = 100000; 63 | 64 | @Disabled("성능 테스트는 반복적인 실행이 불필요하다.") 65 | @Test 66 | @DisplayName("Synchronized 성능 테스트") 67 | void testSynchronizedPerformance() { 68 | SyncExceptionContext syncExceptionContext = new SyncExceptionContext(); 69 | 70 | long startTime = System.nanoTime(); 71 | for (int i = 0; i < NUM_ITERATIONS; i++) { 72 | syncExceptionContext.saveException(new NPlusOneQueryException("Exception " + i)); 73 | } 74 | long endTime = System.nanoTime(); 75 | long duration = endTime - startTime; 76 | System.out.println("Synchronized 소요 시간: " + duration + " ns"); 77 | 78 | syncExceptionContext.clearContext(); 79 | assertThat(duration).isGreaterThan(0); 80 | } 81 | 82 | @Disabled("성능 테스트는 반복적인 실행이 불필요하다.") 83 | @Test 84 | @DisplayName("AtomicReference 성능 테스트") 85 | void testAtomicReferencePerformance() { 86 | ExceptionContextPerformanceTest.AtomicExceptionContext atomicExceptionContext = new AtomicExceptionContext(); 87 | 88 | long startTime = System.nanoTime(); 89 | for (int i = 0; i < NUM_ITERATIONS; i++) { 90 | atomicExceptionContext.saveException(new NPlusOneQueryException("Exception " + i)); 91 | } 92 | long endTime = System.nanoTime(); 93 | long duration = endTime - startTime; 94 | System.out.println("AtomicReference 소요 시간: " + duration + " ns"); 95 | 96 | atomicExceptionContext.clearContext(); 97 | assertThat(duration).isGreaterThan(0); 98 | } 99 | 100 | private static final int NUM_THREADS = 100; 101 | 102 | @Disabled("성능 테스트는 반복적인 실행이 불필요하다.") 103 | @Test 104 | @DisplayName("Synchronized MultiThread 성능 테스트") 105 | void testSynchronizedMultiThreadPerformance() throws InterruptedException { 106 | ExceptionContextPerformanceTest.SyncExceptionContext syncExceptionContext = new SyncExceptionContext(); 107 | ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS); 108 | CountDownLatch countDownLatch = new CountDownLatch(NUM_THREADS); 109 | 110 | long startTime = System.nanoTime(); 111 | 112 | for (int i = 0; i < NUM_THREADS; i++) { 113 | final int threadIndex = i; 114 | executorService.submit(() -> { 115 | try { 116 | for (int j = 0; j < NUM_ITERATIONS / NUM_THREADS; j++) { 117 | syncExceptionContext.saveException( 118 | new NPlusOneQueryException("Exception-" + threadIndex + "-" + j)); 119 | } 120 | } finally { 121 | countDownLatch.countDown(); 122 | } 123 | }); 124 | } 125 | 126 | countDownLatch.await(); 127 | executorService.shutdown(); 128 | 129 | long endTime = System.nanoTime(); 130 | long duration = endTime - startTime; 131 | System.out.println("Synchronized MultiThread 소요 시간: " + duration + " ns"); 132 | 133 | syncExceptionContext.clearContext(); 134 | assertThat(duration).isGreaterThan(0); 135 | } 136 | 137 | @Disabled("성능 테스트는 반복적인 실행이 불필요하다.") 138 | @Test 139 | @DisplayName("AtomicReference MultiThread 성능 테스트") 140 | void testAtomicReferenceMultiThreadPerformance() throws InterruptedException { 141 | AtomicExceptionContext atomicExceptionContext = new AtomicExceptionContext(); 142 | ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS); 143 | CountDownLatch countDownLatch = new CountDownLatch(NUM_THREADS); 144 | 145 | long startTime = System.nanoTime(); 146 | 147 | for (int i = 0; i < NUM_THREADS; i++) { 148 | final int threadIndex = i; 149 | executorService.submit(() -> { 150 | try { 151 | for (int j = 0; j < NUM_ITERATIONS / NUM_THREADS; j++) { 152 | atomicExceptionContext.saveException( 153 | new NPlusOneQueryException("Exception-" + threadIndex + "-" + j)); 154 | } 155 | } finally { 156 | countDownLatch.countDown(); 157 | } 158 | }); 159 | } 160 | 161 | countDownLatch.await(); 162 | executorService.shutdown(); 163 | 164 | long endTime = System.nanoTime(); 165 | long duration = endTime - startTime; 166 | System.out.println("AtomicReference MultiThread 소요 시간: " + duration + " ns"); 167 | 168 | atomicExceptionContext.clearContext(); 169 | assertThat(duration).isGreaterThan(0); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /test/src/test/java/io/jeyong/test/environment/workbench/performance/LoggerPerformanceTest.java: -------------------------------------------------------------------------------- 1 | package io.jeyong.test.environment.workbench.performance; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.Disabled; 9 | import org.junit.jupiter.api.DisplayName; 10 | import org.junit.jupiter.api.Test; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | class LoggerPerformanceTest { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(LoggerPerformanceTest.class); 17 | private static final int queryThreshold = 2; 18 | private static final int DATA_SIZE = 5; 19 | private QueryContext queryContext; 20 | 21 | static class QueryContext { 22 | 23 | private final Map queryCounts = new HashMap<>(); 24 | 25 | public void initTestData(int size) { 26 | for (int i = 0; i < size; i++) { 27 | queryCounts.put("query" + i, (long) (Math.random() * 10)); 28 | } 29 | } 30 | 31 | public Map getQueryCounts() { 32 | return queryCounts; 33 | } 34 | 35 | public void clear() { 36 | queryCounts.clear(); 37 | } 38 | } 39 | 40 | @BeforeEach 41 | public void setUp() { 42 | queryContext = new QueryContext(); 43 | queryContext.initTestData(DATA_SIZE); 44 | } 45 | 46 | @Disabled("성능 테스트는 반복적인 실행이 불필요하다.") 47 | @Test 48 | @DisplayName("forEach 성능 테스트") 49 | public void testForEachPerformance() { 50 | long startTime = System.nanoTime(); 51 | queryContext.getQueryCounts().forEach((query, count) -> { 52 | if (count >= queryThreshold) { 53 | logger.warn("N+1 query detected: '{}' was executed {} times.", query, count); 54 | } 55 | }); 56 | long endTime = System.nanoTime(); 57 | long duration = endTime - startTime; 58 | System.out.println("forEach 소요 시간: " + duration + " ns"); 59 | 60 | queryContext.clear(); 61 | assertThat(duration).isGreaterThan(0); 62 | } 63 | 64 | @Disabled("성능 테스트는 반복적인 실행이 불필요하다.") 65 | @Test 66 | @DisplayName("Stream 성능 테스트") 67 | public void testStreamPerformance() { 68 | long startTime = System.nanoTime(); 69 | queryContext.getQueryCounts().entrySet().stream().forEach(entry -> { 70 | String query = entry.getKey(); 71 | Long count = entry.getValue(); 72 | if (count >= queryThreshold) { 73 | logger.warn("N+1 query detected: '{}' was executed {} times.", query, count); 74 | } 75 | }); 76 | long endTime = System.nanoTime(); 77 | long duration = endTime - startTime; 78 | System.out.println("Stream 소요 시간: " + duration + " ns"); 79 | 80 | queryContext.clear(); 81 | assertThat(duration).isGreaterThan(0); 82 | } 83 | 84 | @Disabled("성능 테스트는 반복적인 실행이 불필요하다.") 85 | @Test 86 | @DisplayName("ParallelStream 성능 테스트") 87 | public void testParallelStreamPerformance() { 88 | long startTime = System.nanoTime(); 89 | queryContext.getQueryCounts().entrySet().parallelStream().forEach(entry -> { 90 | String query = entry.getKey(); 91 | Long count = entry.getValue(); 92 | if (count >= queryThreshold) { 93 | logger.warn("N+1 query detected: '{}' was executed {} times.", query, count); 94 | } 95 | }); 96 | long endTime = System.nanoTime(); 97 | long duration = endTime - startTime; 98 | System.out.println("ParallelStream 소요 시간: " + duration + " ns"); 99 | 100 | queryContext.clear(); 101 | assertThat(duration).isGreaterThan(0); 102 | } 103 | } 104 | --------------------------------------------------------------------------------