├── .github └── workflows │ └── package.yaml ├── .gitignore ├── LICENSE ├── pom.xml ├── readme.md ├── spring-data-criteria-apt ├── pom.xml └── src │ ├── main │ └── java │ │ └── io │ │ └── github │ │ └── holmofy │ │ └── data │ │ └── apt │ │ ├── APTOptions.java │ │ ├── CriteriaGenerator.java │ │ ├── LogHelper.java │ │ └── SpringDataRelationalAnnotationProcessor.java │ └── test │ ├── java │ └── io │ │ └── github │ │ └── holmofy │ │ └── example │ │ └── CompileTest.java │ └── resources │ ├── TestModel.java │ └── TestModel_.java ├── spring-data-criteria-example ├── docker-compose.yaml ├── pom.xml ├── spring-data-criteria-jdbc-example │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── io │ │ │ └── github │ │ │ └── holmofy │ │ │ └── data │ │ │ └── jdbc │ │ │ ├── MainApplication.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── dao │ │ │ └── UserDao.java │ │ │ └── model │ │ │ └── User.java │ │ └── resources │ │ ├── application.properties │ │ └── db │ │ └── migration │ │ └── V1__ddl.sql ├── spring-data-criteria-jpa-example │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── io │ │ │ └── github │ │ │ └── holmofy │ │ │ └── data │ │ │ └── jpa │ │ │ ├── MainApplication.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── dao │ │ │ └── UserDao.java │ │ │ └── model │ │ │ └── User.java │ │ └── resources │ │ ├── application.properties │ │ └── db │ │ └── migration │ │ └── V1__ddl.sql └── spring-data-criteria-r2dbc-example │ ├── pom.xml │ └── src │ └── main │ ├── java │ └── io │ │ └── github │ │ └── holmofy │ │ └── data │ │ └── r2dbc │ │ ├── MainApplication.java │ │ ├── controller │ │ └── UserController.java │ │ ├── dao │ │ └── UserDao.java │ │ └── model │ │ └── User.java │ └── resources │ ├── application.properties │ └── db │ └── migration │ └── V1__ddl.sql ├── spring-data-criteria-jdbc ├── pom.xml ├── readme.md └── src │ └── main │ └── java │ └── io │ └── github │ └── holmofy │ └── data │ └── jdbc │ ├── CriteriaExecutor.java │ ├── EnhancedJdbcRepository.java │ ├── JdbcSupport.java │ └── JdbcSupportImpl.java ├── spring-data-criteria-jpa ├── pom.xml ├── readme.md └── src │ └── main │ └── java │ └── io │ └── github │ └── holmofy │ └── data │ └── jpa │ └── MoreCriteria.java ├── spring-data-criteria-r2dbc ├── pom.xml ├── readme.md └── src │ └── main │ └── java │ └── io │ └── github │ └── holmofy │ └── data │ └── r2dbc │ ├── CriteriaExecutor.java │ ├── EnhancedR2dbcRepository.java │ └── R2dbcSupport.java └── spring-data-criteria-relational ├── pom.xml └── src └── main └── java └── io └── github └── holmofy └── data └── relational └── MoreCriteria.java /.github/workflows/package.yaml: -------------------------------------------------------------------------------- 1 | # This workflow will build a package using Maven and then publish it to GitHub packages when a release is created 2 | # For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#apache-maven-with-a-settings-path 3 | 4 | name: Maven Package 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | paths: 10 | - '**/*.java' 11 | - '**/*.pom' 12 | workflow_dispatch: 13 | inputs: 14 | 15 | jobs: 16 | release: 17 | 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Set up JDK 17 23 | uses: actions/setup-java@v2 24 | with: 25 | java-version: '17' 26 | distribution: 'adopt' 27 | server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml 28 | server-username: MAVEN_USERNAME 29 | server-password: MAVEN_PASSWORD 30 | gpg-private-key: ${{secrets.GPG_PRIVATE_KEY}} 31 | gpg-passphrase: GPG_PASSPHRASE 32 | - name: Publish Package 33 | run: mvn --batch-mode clean deploy 34 | env: 35 | MAVEN_USERNAME: ${{secrets.MAVEN_USERNAME}} 36 | MAVEN_PASSWORD: ${{secrets.MAVEN_PASSWORD}} 37 | GPG_PASSPHRASE: ${{secrets.GPG_PASSPHRASE}} 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/maven,intellij+all,java,macos 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=maven,intellij+all,java,macos 3 | 4 | ### Intellij+all ### 5 | .idea/ 6 | *.iml 7 | 8 | # CMake 9 | cmake-build-*/ 10 | 11 | # Mongo Explorer plugin 12 | .idea/**/mongoSettings.xml 13 | 14 | # File-based project format 15 | *.iws 16 | 17 | # IntelliJ 18 | out/ 19 | 20 | # mpeltonen/sbt-idea plugin 21 | .idea_modules/ 22 | 23 | # JIRA plugin 24 | atlassian-ide-plugin.xml 25 | 26 | # Cursive Clojure plugin 27 | .idea/replstate.xml 28 | 29 | # SonarLint plugin 30 | .idea/sonarlint/ 31 | 32 | # Crashlytics plugin (for Android Studio and IntelliJ) 33 | com_crashlytics_export_strings.xml 34 | crashlytics.properties 35 | crashlytics-build.properties 36 | fabric.properties 37 | 38 | ### Java ### 39 | # Compiled class file 40 | *.class 41 | 42 | # Log file 43 | *.log 44 | 45 | # BlueJ files 46 | *.ctxt 47 | 48 | # Mobile Tools for Java (J2ME) 49 | .mtj.tmp/ 50 | 51 | # Package Files # 52 | *.jar 53 | *.war 54 | *.nar 55 | *.ear 56 | *.zip 57 | *.tar.gz 58 | *.rar 59 | 60 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 61 | hs_err_pid* 62 | replay_pid* 63 | 64 | ### macOS ### 65 | # General 66 | .DS_Store 67 | .AppleDouble 68 | .LSOverride 69 | 70 | # Icon must end with two \r 71 | Icon 72 | 73 | 74 | # Thumbnails 75 | ._* 76 | 77 | # Files that might appear in the root of a volume 78 | .DocumentRevisions-V100 79 | .fseventsd 80 | .Spotlight-V100 81 | .TemporaryItems 82 | .Trashes 83 | .VolumeIcon.icns 84 | .com.apple.timemachine.donotpresent 85 | 86 | # Directories potentially created on remote AFP share 87 | .AppleDB 88 | .AppleDesktop 89 | Network Trash Folder 90 | Temporary Items 91 | .apdisk 92 | 93 | ### macOS Patch ### 94 | # iCloud generated files 95 | *.icloud 96 | 97 | ### Maven ### 98 | target/ 99 | pom.xml.tag 100 | pom.xml.releaseBackup 101 | pom.xml.versionsBackup 102 | pom.xml.next 103 | release.properties 104 | dependency-reduced-pom.xml 105 | buildNumber.properties 106 | .mvn/timing.properties 107 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar 108 | .mvn/wrapper/maven-wrapper.jar 109 | 110 | # Eclipse m2e generated files 111 | # Eclipse Core 112 | .project 113 | # JDT-specific (Eclipse Java Development Tools) 114 | .classpath 115 | **/.flattened-pom.xml 116 | # End of https://www.toptal.com/developers/gitignore/api/maven,intellij+all,java,macos -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | pom 7 | spring-data-criteria 8 | Spring Data Criteria extends Spring Data JDBC & Spring Data R2DBC to support dynamic sql. 9 | 10 | https://github.com/holmofy/spring-data-criteria 11 | 12 | 13 | The Apache Software License, Version 2.0 14 | http://www.apache.org/licenses/LICENSE-2.0.txt 15 | repo 16 | 17 | 18 | 19 | https://github.com/holmofy/spring-data-criteria.git 20 | git@github.com:holmofy/spring-data-criteria.git 21 | https://github.com/holmofy 22 | 23 | 24 | Github 25 | https://github.com/holmofy/spring-data-criteria/issues 26 | 27 | 28 | 29 | holmofy 30 | holmofy 31 | hff1996723@163.com 32 | https://www.hufeifei.cn 33 | +8 34 | 35 | 36 | 37 | spring-data-criteria-apt 38 | spring-data-criteria-jdbc 39 | spring-data-criteria-r2dbc 40 | spring-data-criteria-example 41 | spring-data-criteria-relational 42 | spring-data-criteria-jpa 43 | 44 | 45 | io.github.holmofy 46 | spring-data-criteria 47 | ${reversion} 48 | 49 | 50 | 17 51 | 17 52 | UTF-8 53 | 3.0.6 54 | 1.4.1 55 | 3.2.1 56 | 3.5.0 57 | 3.2.0 58 | 59 | 60 | 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-dependencies 65 | ${spring.boot.version} 66 | pom 67 | import 68 | 69 | 70 | io.github.holmofy 71 | spring-data-criteria-apt 72 | ${project.version} 73 | 74 | 75 | io.github.holmofy 76 | spring-data-criteria-jdbc 77 | ${project.version} 78 | 79 | 80 | io.github.holmofy 81 | spring-data-criteria-r2dbc 82 | ${project.version} 83 | 84 | 85 | io.github.holmofy 86 | spring-data-criteria-relational 87 | ${project.version} 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | org.apache.maven.plugins 96 | maven-gpg-plugin 97 | 98 | 99 | verify 100 | 101 | sign 102 | 103 | 104 | 105 | 106 | 107 | org.apache.maven.plugins 108 | maven-javadoc-plugin 109 | ${maven.javadoc.version} 110 | 111 | 112 | package 113 | 114 | jar 115 | 116 | 117 | 118 | 119 | 120 | org.apache.maven.plugins 121 | maven-source-plugin 122 | ${maven.source.version} 123 | 124 | 125 | package 126 | 127 | jar-no-fork 128 | 129 | 130 | 131 | 132 | 133 | org.sonatype.plugins 134 | nexus-staging-maven-plugin 135 | true 136 | 137 | ossrh 138 | https://s01.oss.sonatype.org/ 139 | false 140 | 141 | 142 | 143 | org.codehaus.mojo 144 | flatten-maven-plugin 145 | ${maven.flatten.version} 146 | 147 | true 148 | resolveCiFriendliesOnly 149 | 150 | 151 | 152 | flatten 153 | process-resources 154 | 155 | flatten 156 | 157 | 158 | 159 | flatten.clean 160 | clean 161 | 162 | clean 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | ossrh 173 | https://s01.oss.sonatype.org/content/repositories/snapshots 174 | 175 | 176 | ossrh 177 | https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/ 178 | 179 | 180 | 181 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | [![Build Status(https://github.com/holmofy/spring-data-jdbc-criteria/actions/workflows/package.yaml/badge.svg)](https://github.com/holmofy/spring-data-jdbc-criteria/actions/workflows/package.yaml/badge.svg)](https://repo1.maven.org/maven2/io/github/holmofy/) 2 | 3 | `Spring Data Criteria` extends Spring Data JDBC & Spring Data R2DBC & Spring Data JPA to support dynamic sql. 4 | 5 | to see [`DATAJDBC-319`](https://github.com/spring-projects/spring-data-relational/issues/542), [`DATAJPA-2724`](https://github.com/spring-projects/spring-data-jpa/issues/2724). 6 | 7 | The usage is as follows: 8 | 9 | ```java 10 | public interface UserDao extends ListCrudRepository, CriteriaExecutor { 11 | default Page searchByQuery(UserQuery query, Pageable pageable) { 12 | return findAll(Criteria.from(eq(User_.province, query.province)) 13 | .and(eq(User_.city, query.city)) 14 | .and(like(User_.area, query.area)) 15 | .and(like(User_.name, query.nick)) 16 | .and(between(User_.created, query.createFrom, query.createTo)) 17 | , pageable); 18 | } 19 | } 20 | ``` 21 | 22 | It will dynamically generate sql based on whether the query field is empty. 23 | 24 | ## How to use 25 | 26 | * [Using it with `spring-data-jdbc`](./spring-data-criteria-jdbc) 27 | * [Using it with `spring-data-jpa`](./spring-data-criteria-jpa) 28 | * [Using it with `spring-data-r2dbc`](./spring-data-criteria-r2dbc) 29 | 30 | -------------------------------------------------------------------------------- /spring-data-criteria-apt/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-criteria 7 | io.github.holmofy 8 | ${reversion} 9 | 10 | 4.0.0 11 | jar 12 | 13 | spring-data-criteria-apt 14 | 15 | 16 | 3.10.1 17 | 17 18 | 17 19 | UTF-8 20 | 21 | 22 | 23 | 24 | org.springframework.data 25 | spring-data-relational 26 | 27 | 28 | org.projectlombok 29 | lombok 30 | provided 31 | 32 | 33 | com.google.auto.service 34 | auto-service 35 | 1.0.1 36 | 37 | 38 | com.squareup 39 | javapoet 40 | 1.13.0 41 | 42 | 43 | com.google.testing.compile 44 | compile-testing 45 | 0.20 46 | test 47 | 48 | 49 | junit 50 | junit 51 | test 52 | 53 | 54 | 55 | 56 | 57 | 58 | org.apache.maven.plugins 59 | maven-compiler-plugin 60 | ${maven-compiler-plugin.version} 61 | 62 | 63 | 64 | org.projectlombok 65 | lombok 66 | 1.18.24 67 | 68 | 69 | com.google.auto.service 70 | auto-service 71 | 1.0.1 72 | 73 | 74 | 75 | 76 | 77 | org.apache.maven.plugins 78 | maven-surefire-plugin 79 | 3.0.0 80 | 81 | 82 | --add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED 83 | --add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED 84 | --add-opens=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /spring-data-criteria-apt/src/main/java/io/github/holmofy/data/apt/APTOptions.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.apt; 2 | 3 | public interface APTOptions { 4 | 5 | String show_log = "spring.data.jdbc.annotation.processor.show_log"; 6 | 7 | } 8 | -------------------------------------------------------------------------------- /spring-data-criteria-apt/src/main/java/io/github/holmofy/data/apt/CriteriaGenerator.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.apt; 2 | 3 | import com.google.common.base.CaseFormat; 4 | import com.google.common.base.Converter; 5 | import com.squareup.javapoet.*; 6 | import lombok.Data; 7 | import lombok.SneakyThrows; 8 | import org.springframework.data.annotation.Transient; 9 | import org.springframework.data.relational.core.mapping.Column; 10 | import org.springframework.data.relational.core.mapping.Embedded; 11 | import org.springframework.data.relational.core.mapping.Table; 12 | import org.springframework.data.relational.core.sql.SQL; 13 | import org.springframework.util.StringUtils; 14 | 15 | import javax.annotation.processing.Generated; 16 | import javax.annotation.processing.ProcessingEnvironment; 17 | import javax.lang.model.element.*; 18 | import javax.lang.model.type.TypeMirror; 19 | import javax.tools.Diagnostic; 20 | import java.util.List; 21 | import java.util.Objects; 22 | import java.util.Optional; 23 | import java.util.stream.Collectors; 24 | 25 | public class CriteriaGenerator { 26 | 27 | private final LogHelper logger; 28 | private final ProcessingEnvironment processingEnv; 29 | 30 | public CriteriaGenerator(LogHelper logger, ProcessingEnvironment processingEnv) { 31 | this.logger = logger; 32 | this.processingEnv = processingEnv; 33 | } 34 | 35 | @SneakyThrows 36 | public void generateSource(TypeElement table) { 37 | TableModel model = analysisFields(table); 38 | JavaFile javaFile = model.generateSource(); 39 | javaFile.writeTo(processingEnv.getFiler()); 40 | } 41 | 42 | private TableModel analysisFields(TypeElement type) { 43 | TableModel tableModel = new TableModel(); 44 | tableModel.setClassElement(type); 45 | tableModel.setPackageElement(processingEnv.getElementUtils().getPackageOf(type)); 46 | tableModel.setFields(collectFields(type)); 47 | return tableModel; 48 | } 49 | 50 | private List collectFields(TypeElement type) { 51 | return processingEnv.getElementUtils() 52 | .getAllMembers(type) 53 | .stream() 54 | .map(this::filterFields) 55 | .filter(Objects::nonNull) 56 | .collect(Collectors.toList()); 57 | } 58 | 59 | private VariableElement filterFields(Element field) { 60 | if (field.getKind() != ElementKind.FIELD) { 61 | return null; 62 | } 63 | VariableElement f = (VariableElement) field; 64 | if (f.getModifiers().contains(Modifier.STATIC)) { 65 | return null; 66 | } 67 | if (f.getAnnotation(Transient.class) != null) { 68 | return null; 69 | } 70 | return f; 71 | } 72 | 73 | @Data 74 | public class TableModel { 75 | 76 | public static final String SPRING_DATA_PACKAGE = "org.springframework.data.relational.core.sql"; 77 | 78 | private static final Converter LOWER_UNDERSCORE = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.LOWER_UNDERSCORE); 79 | private static final Converter UPPER_UNDERSCORE = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE); 80 | 81 | private PackageElement packageElement; 82 | 83 | private TypeElement classElement; 84 | 85 | private List fields; 86 | 87 | public JavaFile generateSource() { 88 | TypeSpec.Builder builder = TypeSpec.classBuilder(getGenerateClassName()) 89 | .addModifiers(Modifier.PUBLIC, Modifier.FINAL); 90 | 91 | /** 92 | * @Generated(value = "io.github.holmofy.data.apt.SpringDataRelationalAnnotationProcessor") 93 | */ 94 | builder.addAnnotation(AnnotationSpec.builder(Generated.class) 95 | .addMember("value", "$S", SpringDataRelationalAnnotationProcessor.class.getCanonicalName()) 96 | .build() 97 | ); 98 | 99 | // table name 100 | String tableName = getTableName(); 101 | builder.addField(FieldSpec.builder( 102 | ClassName.get(String.class), "TABLE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL 103 | ).initializer("$S", tableName).build()); 104 | builder.addField(FieldSpec.builder( 105 | ClassName.get(org.springframework.data.relational.core.sql.Table.class), "TABLE", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL 106 | ).initializer("$T.table(TABLE_NAME)", SQL.class).build()); 107 | 108 | addFields(builder, this.fields, ""); 109 | 110 | TypeSpec type = builder.build(); 111 | return JavaFile.builder(packageElement.getQualifiedName().toString(), type) 112 | .build(); 113 | } 114 | 115 | private void addFields(TypeSpec.Builder builder, List fields, String columnPrefix) { 116 | for (VariableElement field : fields) { 117 | Embedded embedded = field.getAnnotation(Embedded.class); 118 | Embedded.Empty embeddedEmpty = field.getAnnotation(Embedded.Empty.class); 119 | Embedded.Nullable embeddedNullable = field.getAnnotation(Embedded.Nullable.class); 120 | if (embedded == null && embeddedEmpty == null && embeddedNullable == null) { 121 | addField(builder, field, columnPrefix); 122 | continue; 123 | } 124 | String prefix = embedded != null ? embedded.prefix() : 125 | embeddedEmpty != null ? embeddedEmpty.prefix() : embeddedNullable.prefix(); 126 | TypeMirror typeMirror = field.asType(); 127 | if (typeMirror.getKind().isPrimitive()) { 128 | logger.log(Diagnostic.Kind.WARNING, "@Embedded field is primitive"); 129 | } else { 130 | Element element = processingEnv.getTypeUtils().asElement(typeMirror); 131 | if (element.getKind().isClass()) { 132 | addFields(builder, collectFields((TypeElement) element), prefix); 133 | } 134 | } 135 | } 136 | } 137 | 138 | private void addField(TypeSpec.Builder builder, VariableElement field, String columnPrefix) { 139 | String fieldName = field.getSimpleName().toString(); 140 | String column_name = Optional.of(field).map(f -> f.getAnnotation(Column.class)) 141 | .map(Column::value) 142 | .filter(s -> !s.isBlank()) 143 | .orElse(LOWER_UNDERSCORE.convert(fieldName)); 144 | builder.addField(FieldSpec.builder( 145 | ClassName.get(String.class), fieldName, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL 146 | ).initializer("$S", columnPrefix + column_name).build()); 147 | String COLUMN_NAME = Objects.requireNonNull(UPPER_UNDERSCORE.convert(fieldName)); 148 | builder.addField(FieldSpec.builder( 149 | ClassName.get(org.springframework.data.relational.core.sql.Column.class), COLUMN_NAME, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL 150 | ).initializer("$T.column($L, TABLE)", SQL.class, fieldName).build()); 151 | } 152 | 153 | public String getGenerateClassName() { 154 | return classElement.getSimpleName() + "_"; 155 | } 156 | 157 | private String getTableName() { 158 | Table annotation = classElement.getAnnotation(Table.class); 159 | if (annotation != null) { 160 | if (StringUtils.hasLength(annotation.name())) { 161 | return annotation.name(); 162 | } 163 | if (StringUtils.hasLength(annotation.value())) { 164 | return annotation.value(); 165 | } 166 | } 167 | return LOWER_UNDERSCORE.convert(classElement.getSimpleName().toString()); 168 | } 169 | } 170 | 171 | } 172 | -------------------------------------------------------------------------------- /spring-data-criteria-apt/src/main/java/io/github/holmofy/data/apt/LogHelper.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.apt; 2 | 3 | import javax.annotation.processing.ProcessingEnvironment; 4 | import javax.tools.Diagnostic; 5 | 6 | public class LogHelper { 7 | 8 | private final ProcessingEnvironment processingEnv; 9 | private final boolean shouldLogInfo; 10 | 11 | public LogHelper(ProcessingEnvironment processingEnv) { 12 | this.processingEnv = processingEnv; 13 | this.shouldLogInfo = processingEnv.getOptions().containsKey(APTOptions.show_log); 14 | } 15 | 16 | public void log(Diagnostic.Kind kind, String message) { 17 | if (shouldLogInfo) { 18 | processingEnv.getMessager().printMessage(kind, message); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /spring-data-criteria-apt/src/main/java/io/github/holmofy/data/apt/SpringDataRelationalAnnotationProcessor.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.apt; 2 | 3 | import com.google.auto.service.AutoService; 4 | import lombok.SneakyThrows; 5 | import org.springframework.data.relational.core.mapping.Table; 6 | 7 | import javax.annotation.processing.*; 8 | import javax.lang.model.SourceVersion; 9 | import javax.lang.model.element.Element; 10 | import javax.lang.model.element.ElementKind; 11 | import javax.lang.model.element.TypeElement; 12 | import javax.tools.Diagnostic; 13 | import java.util.Set; 14 | 15 | @AutoService(Processor.class) 16 | @SupportedOptions(APTOptions.show_log) 17 | @SupportedSourceVersion(SourceVersion.RELEASE_17) 18 | @SupportedAnnotationTypes("org.springframework.data.relational.core.mapping.Table") 19 | public class SpringDataRelationalAnnotationProcessor extends AbstractProcessor { 20 | 21 | public static final Boolean ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS = Boolean.FALSE; 22 | 23 | @Override 24 | @SneakyThrows 25 | public boolean process(Set annotations, RoundEnvironment roundEnv) { 26 | LogHelper logger = new LogHelper(processingEnv); 27 | if (roundEnv.processingOver() || annotations.size() == 0) { 28 | return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS; 29 | } 30 | 31 | if (roundEnv.getRootElements() == null || roundEnv.getRootElements().isEmpty()) { 32 | logger.log(Diagnostic.Kind.NOTE, "No sources to process"); 33 | return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS; 34 | } 35 | 36 | Set tables = roundEnv.getElementsAnnotatedWith(Table.class); 37 | CriteriaGenerator criteriaGenerator = new CriteriaGenerator(logger, processingEnv); 38 | for (Element table : tables) { 39 | if (table.getKind() != ElementKind.CLASS) { 40 | logger.log(Diagnostic.Kind.ERROR, "@Table should be placed at the class level"); 41 | continue; 42 | } 43 | criteriaGenerator.generateSource((TypeElement) table); 44 | } 45 | 46 | return true; 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /spring-data-criteria-apt/src/test/java/io/github/holmofy/example/CompileTest.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.example; 2 | 3 | import com.google.testing.compile.Compilation; 4 | import com.google.testing.compile.Compiler; 5 | import com.google.testing.compile.JavaFileObjects; 6 | import io.github.holmofy.data.apt.SpringDataRelationalAnnotationProcessor; 7 | import org.junit.Test; 8 | 9 | import static com.google.testing.compile.CompilationSubject.assertThat; 10 | 11 | public class CompileTest { 12 | 13 | @Test 14 | public void test() { 15 | Compilation compilation = 16 | Compiler.javac() 17 | .withProcessors(new SpringDataRelationalAnnotationProcessor()) 18 | .compile(JavaFileObjects.forResource("TestModel.java")); 19 | assertThat(compilation).succeeded(); 20 | assertThat(compilation) 21 | .generatedSourceFile("io.github.holmofy.example.TestModel_") 22 | .hasSourceEquivalentTo(JavaFileObjects.forResource("TestModel_.java")); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /spring-data-criteria-apt/src/test/resources/TestModel.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.example; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.Id; 5 | import org.springframework.data.annotation.Transient; 6 | import org.springframework.data.relational.core.mapping.Column; 7 | import org.springframework.data.relational.core.mapping.Embedded; 8 | import org.springframework.data.relational.core.mapping.Table; 9 | 10 | @Data 11 | @Table("test_model") 12 | public class TestModel { 13 | 14 | @Id 15 | private Long id; 16 | 17 | @Column("named_column") 18 | private String withColumn; 19 | 20 | private String lowerCamel; 21 | 22 | @Transient 23 | private String transientField; 24 | 25 | @Embedded(onEmpty = Embedded.OnEmpty.USE_EMPTY, prefix = "embedded_") 26 | private EmbeddedProperties embeddedField; 27 | 28 | // @Embedded.Empty 29 | // private EmptyEmbeddedProperties embeddedEmptyField; 30 | 31 | @Data 32 | public static class EmbeddedProperties { 33 | private String field1; 34 | @Column("field_2") 35 | private String field2; 36 | } 37 | 38 | @Data 39 | public static class EmptyEmbeddedProperties { 40 | private String field3; 41 | @Column("field_4") 42 | private String field4; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /spring-data-criteria-apt/src/test/resources/TestModel_.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.example; 2 | 3 | import java.lang.String; 4 | import javax.annotation.processing.Generated; 5 | import org.springframework.data.relational.core.sql.Column; 6 | import org.springframework.data.relational.core.sql.SQL; 7 | import org.springframework.data.relational.core.sql.Table; 8 | 9 | @Generated("io.github.holmofy.data.apt.SpringDataRelationalAnnotationProcessor") 10 | public final class TestModel_ { 11 | public static final String TABLE_NAME = "test_model"; 12 | public static final Table TABLE = SQL.table(TABLE_NAME); 13 | 14 | public static final String id = "id"; 15 | public static final Column ID = SQL.column(id, TABLE); 16 | 17 | public static final String withColumn = "named_column"; 18 | public static final Column WITH_COLUMN = SQL.column(withColumn, TABLE); 19 | 20 | public static final String lowerCamel = "lower_camel"; 21 | public static final Column LOWER_CAMEL = SQL.column(lowerCamel, TABLE); 22 | 23 | public static final String field1 = "embedded_field1"; 24 | public static final Column FIELD1 = SQL.column(field1, TABLE); 25 | 26 | public static final String field2 = "embedded_field_2"; 27 | public static final Column FIELD2 = SQL.column(field2, TABLE); 28 | } -------------------------------------------------------------------------------- /spring-data-criteria-example/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | postgres: 5 | image: postgres:15.2-alpine 6 | environment: 7 | - POSTGRES_PASSWORD=123456 8 | ports: 9 | - 5432:5432 -------------------------------------------------------------------------------- /spring-data-criteria-example/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-criteria 7 | io.github.holmofy 8 | ${reversion} 9 | 10 | 4.0.0 11 | pom 12 | 13 | spring-data-criteria-example 14 | 15 | 16 | spring-data-criteria-jdbc-example 17 | spring-data-criteria-r2dbc-example 18 | spring-data-criteria-jpa-example 19 | 20 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jdbc-example/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | io.github.holmofy 7 | spring-data-criteria-example 8 | ${reversion} 9 | 10 | 4.0.0 11 | jar 12 | 13 | spring-data-jdbc-criteria-example 14 | 15 | 16 | 3.10.1 17 | UTF-8 18 | 17 19 | 17 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-data-jdbc 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | io.github.holmofy 33 | spring-data-criteria-jdbc 34 | ${reversion} 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | 40 | 41 | org.flywaydb 42 | flyway-core 43 | 44 | 45 | org.postgresql 46 | postgresql 47 | runtime 48 | 49 | 50 | ch.qos.logback 51 | logback-classic 52 | 53 | 54 | 55 | 56 | 57 | 58 | org.apache.maven.plugins 59 | maven-compiler-plugin 60 | ${maven-compiler-plugin.version} 61 | 62 | ${maven.compiler.source} 63 | ${maven.compiler.target} 64 | 65 | 66 | org.projectlombok 67 | lombok 68 | 1.18.24 69 | 70 | 71 | io.github.holmofy 72 | spring-data-criteria-apt 73 | ${reversion} 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jdbc-example/src/main/java/io/github/holmofy/data/jdbc/MainApplication.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jdbc; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories; 6 | 7 | @SpringBootApplication 8 | @EnableJdbcRepositories(repositoryBaseClass = EnhancedJdbcRepository.class) 9 | public class MainApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(MainApplication.class, args); 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jdbc-example/src/main/java/io/github/holmofy/data/jdbc/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jdbc.controller; 2 | 3 | import io.github.holmofy.data.jdbc.dao.UserDao; 4 | import io.github.holmofy.data.jdbc.model.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.util.List; 12 | 13 | @RestController 14 | public class UserController { 15 | 16 | @Autowired 17 | UserDao userDao; 18 | 19 | @GetMapping("/search") 20 | public Page search(UserDao.UserQuery query, Pageable pageable) { 21 | return userDao.searchByQuery(query, pageable); 22 | } 23 | 24 | @GetMapping("/search-list1") 25 | public List search1(UserDao.UserQuery query) { 26 | return userDao.searchByQuery1(query); 27 | } 28 | 29 | @GetMapping("/search-list2") 30 | public List search2(UserDao.UserQuery query) { 31 | return userDao.searchByQuery2(query); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jdbc-example/src/main/java/io/github/holmofy/data/jdbc/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jdbc.dao; 2 | 3 | import io.github.holmofy.data.jdbc.CriteriaExecutor; 4 | import io.github.holmofy.data.jdbc.JdbcSupport; 5 | import io.github.holmofy.data.jdbc.model.User; 6 | import io.github.holmofy.data.jdbc.model.User_; 7 | import io.github.holmofy.data.relational.MoreCriteria; 8 | import lombok.Data; 9 | import org.springframework.data.domain.Page; 10 | import org.springframework.data.domain.Pageable; 11 | import org.springframework.data.relational.core.query.Criteria; 12 | import org.springframework.data.relational.core.sql.Conditions; 13 | import org.springframework.data.relational.core.sql.SQL; 14 | import org.springframework.data.relational.core.sql.Select; 15 | import org.springframework.data.relational.core.sql.render.SqlRenderer; 16 | import org.springframework.data.repository.ListCrudRepository; 17 | import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; 18 | 19 | import java.time.LocalDateTime; 20 | import java.util.List; 21 | 22 | public interface UserDao extends ListCrudRepository, CriteriaExecutor, JdbcSupport { 23 | 24 | default List searchByQuery1(UserQuery query) { 25 | Select sql = Select.builder().select() 26 | .from(User_.TABLE) 27 | .where(Conditions.isEqual(User_.PROVINCE, SQL.bindMarker(":province"))) 28 | .and(Conditions.isEqual(User_.CITY, SQL.bindMarker(":city"))) 29 | .and(Conditions.isEqual(User_.AREA, SQL.bindMarker(":area"))) 30 | .and(Conditions.isEqual(User_.NAME, SQL.bindMarker(":nick"))) 31 | .build(); 32 | return namedJdbcTemplate().queryForList(SqlRenderer.toString(sql) 33 | , new BeanPropertySqlParameterSource(query), User.class); 34 | } 35 | 36 | default List searchByQuery2(UserQuery query) { 37 | return namedJdbcTemplate().queryForList( 38 | "select * " + 39 | "from t_user " + 40 | "where 1=1 " + 41 | (query.province == null ? "" : "and province=:province ") + 42 | (query.city == null ? "" : "and city=:city ") + 43 | (query.area == null ? "" : "and area=:area ") + 44 | (query.nick == null ? "" : "and nick=:nick ") 45 | , new BeanPropertySqlParameterSource(query), User.class); 46 | } 47 | 48 | default Page searchByQuery(UserQuery query, Pageable pageable) { 49 | return findAll(Criteria.from(MoreCriteria.eq(User_.province, query.province)) 50 | .and(MoreCriteria.eq(User_.city, query.city)) 51 | .and(MoreCriteria.like(User_.area, query.area)) 52 | .and(MoreCriteria.like(User_.name, query.nick)) 53 | .and(MoreCriteria.between(User_.created, query.createFrom, query.createTo)) 54 | , pageable); 55 | } 56 | 57 | @Data 58 | class UserQuery { 59 | String nick; 60 | String province; 61 | String city; 62 | String area; 63 | LocalDateTime createFrom; 64 | LocalDateTime createTo; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jdbc-example/src/main/java/io/github/holmofy/data/jdbc/model/User.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jdbc.model; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.CreatedDate; 5 | import org.springframework.data.annotation.Id; 6 | import org.springframework.data.annotation.LastModifiedDate; 7 | import org.springframework.data.relational.core.mapping.Column; 8 | import org.springframework.data.relational.core.mapping.Embedded; 9 | import org.springframework.data.relational.core.mapping.Table; 10 | 11 | import java.time.LocalDateTime; 12 | 13 | @Data 14 | @Table("t_user") 15 | public class User { 16 | 17 | @Id 18 | private Long id; 19 | 20 | @Column("nick") 21 | private String name; 22 | 23 | @Embedded.Empty 24 | private Address address; 25 | 26 | @CreatedDate 27 | @Column("created_date") 28 | private LocalDateTime created; 29 | 30 | @LastModifiedDate 31 | @Column("last_modified_date") 32 | private LocalDateTime modified; 33 | 34 | @Data 35 | public static class Address { 36 | private String province; 37 | private String city; 38 | private String area; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jdbc-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:postgresql://localhost:5432/postgres 2 | spring.datasource.username=postgres 3 | spring.datasource.password=123456 4 | spring.flyway.baseline-on-migrate=true 5 | spring.flyway.baseline-version=0 6 | debug=true 7 | server.port=8888 -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jdbc-example/src/main/resources/db/migration/V1__ddl.sql: -------------------------------------------------------------------------------- 1 | create sequence t_user_seq; 2 | 3 | create table if not exists t_user( 4 | id bigint primary key default nextval('t_user_seq'), 5 | nick varchar(32) not null, 6 | province varchar(32) not null, 7 | city varchar(32) not null, 8 | area varchar(128) not null, 9 | created_date timestamp not null, 10 | last_modified_date timestamp not null 11 | ); 12 | 13 | insert into t_user 14 | (nick,province,city,area,created_date,last_modified_date) 15 | values 16 | ('Tom','JiangXi','NanChang','Qingshanhu',now(),now()), 17 | ('Jerry','JiangXi','JiuJiang','DuChange',now(),now()), 18 | ('Bob','JiangXi','NanChang','Qingshanhu',now(),now()), 19 | ('Lucy','JiangXi','NanChang','Qingshanhu',now(),now()), 20 | ('Jack','JiangXi','NanChang','Qingshanhu',now(),now()); -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jpa-example/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-criteria-example 7 | io.github.holmofy 8 | ${reversion} 9 | 10 | 4.0.0 11 | 12 | spring-data-criteria-jpa-example 13 | 14 | 15 | 3.10.1 16 | 17 17 | 17 18 | UTF-8 19 | 20 | 21 | 22 | 23 | org.hibernate.orm 24 | hibernate-core 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-data-jpa 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | io.github.holmofy 36 | spring-data-criteria-jpa 37 | ${reversion} 38 | 39 | 40 | org.projectlombok 41 | lombok 42 | 43 | 44 | org.flywaydb 45 | flyway-core 46 | 47 | 48 | org.postgresql 49 | postgresql 50 | runtime 51 | 52 | 53 | ch.qos.logback 54 | logback-classic 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.apache.maven.plugins 62 | maven-compiler-plugin 63 | ${maven-compiler-plugin.version} 64 | 65 | ${maven.compiler.source} 66 | ${maven.compiler.target} 67 | 68 | 69 | org.projectlombok 70 | lombok 71 | 1.18.24 72 | 73 | 74 | org.hibernate.orm 75 | hibernate-jpamodelgen 76 | 6.1.7.Final 77 | 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jpa-example/src/main/java/io/github/holmofy/data/jpa/MainApplication.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jpa; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 6 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 7 | 8 | @EnableJpaAuditing 9 | @EnableJpaRepositories 10 | @SpringBootApplication 11 | public class MainApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(MainApplication.class, args); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jpa-example/src/main/java/io/github/holmofy/data/jpa/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jpa.controller; 2 | 3 | import io.github.holmofy.data.jpa.dao.UserDao; 4 | import io.github.holmofy.data.jpa.model.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | public class UserController { 13 | 14 | @Autowired 15 | UserDao userDao; 16 | 17 | @GetMapping("/search") 18 | public Page search(UserDao.UserQuery query, Pageable pageable) { 19 | return userDao.searchByQuery(query, pageable); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jpa-example/src/main/java/io/github/holmofy/data/jpa/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jpa.dao; 2 | 3 | import io.github.holmofy.data.jpa.MoreCriteria; 4 | import io.github.holmofy.data.jpa.model.User; 5 | import io.github.holmofy.data.jpa.model.User_; 6 | import lombok.Data; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.data.jpa.domain.Specification; 10 | import org.springframework.data.jpa.repository.JpaRepository; 11 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 12 | 13 | import java.time.LocalDateTime; 14 | 15 | public interface UserDao extends JpaRepository, JpaSpecificationExecutor { 16 | 17 | default Page searchByQuery(UserQuery query, Pageable pageable) { 18 | return findAll(Specification.where(MoreCriteria.eq(User_.province, query.province)) 19 | .and(MoreCriteria.eq(User_.city, query.city)) 20 | .and(MoreCriteria.like(User_.area, query.area)) 21 | .and(MoreCriteria.like(User_.name, query.nick)) 22 | .and(MoreCriteria.between(User_.created, query.createFrom, query.createTo)) 23 | , pageable); 24 | } 25 | 26 | @Data 27 | class UserQuery { 28 | String nick; 29 | String province; 30 | String city; 31 | String area; 32 | LocalDateTime createFrom; 33 | LocalDateTime createTo; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jpa-example/src/main/java/io/github/holmofy/data/jpa/model/User.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jpa.model; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.Data; 5 | import org.springframework.data.annotation.CreatedDate; 6 | import org.springframework.data.annotation.LastModifiedDate; 7 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 8 | 9 | import java.time.LocalDateTime; 10 | 11 | @Data 12 | @Entity 13 | @Table(name = "t_user") 14 | @EntityListeners(AuditingEntityListener.class) 15 | public class User { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq") 19 | @SequenceGenerator(name = "user_seq", sequenceName = "t_user_seq", allocationSize = 1) 20 | private Long id; 21 | 22 | @Column(name = "nick") 23 | private String name; 24 | 25 | // NOTE: jpamodelgen currently does not support @Embedded 26 | private String province; 27 | private String city; 28 | private String area; 29 | 30 | @CreatedDate 31 | @Column(name = "created_date") 32 | private LocalDateTime created; 33 | 34 | @LastModifiedDate 35 | @Column(name = "last_modified_date") 36 | private LocalDateTime modified; 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jpa-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:postgresql://localhost:5432/postgres 2 | spring.datasource.username=postgres 3 | spring.datasource.password=123456 4 | spring.flyway.baseline-on-migrate=true 5 | spring.flyway.baseline-version=0 6 | debug=true 7 | server.port=8888 -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-jpa-example/src/main/resources/db/migration/V1__ddl.sql: -------------------------------------------------------------------------------- 1 | create sequence t_user_seq; 2 | 3 | create table if not exists t_user( 4 | id bigint primary key default nextval('t_user_seq'), 5 | nick varchar(32) not null, 6 | province varchar(32) not null, 7 | city varchar(32) not null, 8 | area varchar(128) not null, 9 | created_date timestamp not null, 10 | last_modified_date timestamp not null 11 | ); 12 | 13 | insert into t_user 14 | (nick,province,city,area,created_date,last_modified_date) 15 | values 16 | ('Tom','JiangXi','NanChang','Qingshanhu',now(),now()), 17 | ('Jerry','JiangXi','JiuJiang','DuChange',now(),now()), 18 | ('Bob','JiangXi','NanChang','Qingshanhu',now(),now()), 19 | ('Lucy','JiangXi','NanChang','Qingshanhu',now(),now()), 20 | ('Jack','JiangXi','NanChang','Qingshanhu',now(),now()); -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-r2dbc-example/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-criteria-example 7 | io.github.holmofy 8 | ${reversion} 9 | 10 | 4.0.0 11 | 12 | spring-data-criteria-r2dbc-example 13 | 14 | 15 | 3.10.1 16 | 17 17 | 17 18 | UTF-8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-data-r2dbc 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-webflux 29 | 30 | 31 | io.github.holmofy 32 | spring-data-criteria-r2dbc 33 | 34 | 35 | org.projectlombok 36 | lombok 37 | 38 | 39 | org.postgresql 40 | postgresql 41 | runtime 42 | 43 | 44 | org.postgresql 45 | r2dbc-postgresql 46 | runtime 47 | 48 | 49 | ch.qos.logback 50 | logback-classic 51 | 52 | 53 | 54 | 55 | 56 | 57 | org.apache.maven.plugins 58 | maven-compiler-plugin 59 | ${maven-compiler-plugin.version} 60 | 61 | ${maven.compiler.source} 62 | ${maven.compiler.target} 63 | 64 | 65 | org.projectlombok 66 | lombok 67 | 1.18.24 68 | 69 | 70 | io.github.holmofy 71 | spring-data-criteria-apt 72 | ${reversion} 73 | 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-r2dbc-example/src/main/java/io/github/holmofy/data/r2dbc/MainApplication.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.r2dbc; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories; 7 | import org.springframework.data.web.ReactivePageableHandlerMethodArgumentResolver; 8 | import org.springframework.data.web.ReactiveSortHandlerMethodArgumentResolver; 9 | import org.springframework.web.reactive.config.WebFluxConfigurer; 10 | import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer; 11 | 12 | @SpringBootApplication 13 | @EnableR2dbcRepositories(repositoryBaseClass = EnhancedR2dbcRepository.class) 14 | public class MainApplication { 15 | 16 | public static void main(String[] args) { 17 | SpringApplication.run(MainApplication.class, args); 18 | } 19 | 20 | @Bean 21 | WebFluxConfigurer springDataArgumentResolversConfigurer() { 22 | return new WebFluxConfigurer() { 23 | 24 | @Override 25 | public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) { 26 | configurer.addCustomResolver(new ReactiveSortHandlerMethodArgumentResolver(), 27 | new ReactivePageableHandlerMethodArgumentResolver()); 28 | } 29 | }; 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-r2dbc-example/src/main/java/io/github/holmofy/data/r2dbc/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.r2dbc.controller; 2 | 3 | import io.github.holmofy.data.r2dbc.dao.UserDao; 4 | import io.github.holmofy.data.r2dbc.model.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | import reactor.core.publisher.Mono; 11 | 12 | @RestController 13 | public class UserController { 14 | 15 | @Autowired 16 | UserDao userDao; 17 | 18 | @GetMapping("/search") 19 | public Mono> search(UserDao.UserQuery query, Pageable pageable) { 20 | return userDao.searchByQuery(query, pageable); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-r2dbc-example/src/main/java/io/github/holmofy/data/r2dbc/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.r2dbc.dao; 2 | 3 | import io.github.holmofy.data.r2dbc.CriteriaExecutor; 4 | import io.github.holmofy.data.r2dbc.model.User; 5 | import io.github.holmofy.data.r2dbc.model.User_; 6 | import io.github.holmofy.data.relational.MoreCriteria; 7 | import lombok.Data; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.Pageable; 10 | import org.springframework.data.relational.core.query.Criteria; 11 | import org.springframework.data.repository.ListCrudRepository; 12 | import reactor.core.publisher.Mono; 13 | 14 | import java.time.LocalDateTime; 15 | 16 | public interface UserDao extends ListCrudRepository, CriteriaExecutor { 17 | 18 | default Mono> searchByQuery(UserQuery query, Pageable pageable) { 19 | return findAll(Criteria.from(MoreCriteria.eq(User_.province, query.province)) 20 | .and(MoreCriteria.eq(User_.city, query.city)) 21 | .and(MoreCriteria.like(User_.area, query.area)) 22 | .and(MoreCriteria.like(User_.name, query.nick)) 23 | .and(MoreCriteria.between(User_.created, query.createFrom, query.createTo)) 24 | , pageable); 25 | } 26 | 27 | @Data 28 | class UserQuery { 29 | String nick; 30 | String province; 31 | String city; 32 | String area; 33 | LocalDateTime createFrom; 34 | LocalDateTime createTo; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-r2dbc-example/src/main/java/io/github/holmofy/data/r2dbc/model/User.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.r2dbc.model; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.CreatedDate; 5 | import org.springframework.data.annotation.Id; 6 | import org.springframework.data.annotation.LastModifiedDate; 7 | import org.springframework.data.relational.core.mapping.Column; 8 | import org.springframework.data.relational.core.mapping.Embedded; 9 | import org.springframework.data.relational.core.mapping.Table; 10 | 11 | import java.time.LocalDateTime; 12 | 13 | @Data 14 | @Table("t_user") 15 | public class User { 16 | 17 | @Id 18 | private Long id; 19 | 20 | @Column("nick") 21 | private String name; 22 | 23 | // NOTE: spring-data-r2dbc currently does not support @Embedded 24 | private String province; 25 | private String city; 26 | private String area; 27 | 28 | @CreatedDate 29 | @Column("created_date") 30 | private LocalDateTime created; 31 | 32 | @LastModifiedDate 33 | @Column("last_modified_date") 34 | private LocalDateTime modified; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-r2dbc-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.r2dbc.url=r2dbc:postgresql://localhost:5432/postgres 2 | spring.r2dbc.username=postgres 3 | spring.r2dbc.password=123456 4 | spring.flyway.baseline-on-migrate=true 5 | spring.flyway.baseline-version=0 6 | debug=true 7 | server.port=8888 -------------------------------------------------------------------------------- /spring-data-criteria-example/spring-data-criteria-r2dbc-example/src/main/resources/db/migration/V1__ddl.sql: -------------------------------------------------------------------------------- 1 | create sequence t_user_seq; 2 | 3 | create table if not exists t_user( 4 | id bigint primary key default nextval('t_user_seq'), 5 | nick varchar(32) not null, 6 | province varchar(32) not null, 7 | city varchar(32) not null, 8 | area varchar(128) not null, 9 | created_date timestamp not null, 10 | last_modified_date timestamp not null 11 | ); 12 | 13 | insert into t_user 14 | (nick,province,city,area,created_date,last_modified_date) 15 | values 16 | ('Tom','JiangXi','NanChang','Qingshanhu',now(),now()), 17 | ('Jerry','JiangXi','JiuJiang','DuChange',now(),now()), 18 | ('Bob','JiangXi','NanChang','Qingshanhu',now(),now()), 19 | ('Lucy','JiangXi','NanChang','Qingshanhu',now(),now()), 20 | ('Jack','JiangXi','NanChang','Qingshanhu',now(),now()); -------------------------------------------------------------------------------- /spring-data-criteria-jdbc/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-criteria 7 | io.github.holmofy 8 | ${reversion} 9 | 10 | 4.0.0 11 | jar 12 | 13 | spring-data-criteria-jdbc 14 | 15 | 16 | 17 | org.springframework.data 18 | spring-data-relational 19 | 20 | 21 | org.springframework.data 22 | spring-data-jdbc 23 | 24 | 25 | io.github.holmofy 26 | spring-data-criteria-relational 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /spring-data-criteria-jdbc/readme.md: -------------------------------------------------------------------------------- 1 | ## How to use 2 | 3 | 1、add dependency 4 | ```xml 5 | 6 | io.github.holmofy 7 | spring-data-criteria-jdbc 8 | ${latest-version} 9 | 10 | ``` 11 | 12 | Find the latest version [here](https://repo1.maven.org/maven2/io/github/holmofy/spring-data-criteria-jdbc) 13 | 14 | 2、add apt plugin. It is like `hibernate-jpamodelgen`, which will help you generate corresponding mapping fields according to the model of SpringData 15 | ```xml 16 | 17 | 18 | 19 | org.apache.maven.plugins 20 | maven-compiler-plugin 21 | ${maven-compiler-plugin.version} 22 | 23 | ${maven.compiler.source} 24 | ${maven.compiler.target} 25 | 26 | 27 | io.github.holmofy 28 | spring-data-criteria-apt 29 | ${latest-version} 30 | 31 | 32 | 33 | org.projectlombok 34 | lombok 35 | 1.18.24 36 | 37 | 38 | 39 | 40 | 41 | 42 | ``` 43 | 44 | 3、config Spring Data Jdbc: `@EnableJdbcRepositories(repositoryBaseClass = EnhancedJdbcRepository.class)` 45 | 46 | ```java 47 | @SpringBootApplication 48 | @EnableJdbcRepositories(repositoryBaseClass = EnhancedJdbcRepository.class) 49 | public class MainApplication { 50 | 51 | public static void main(String[] args) { 52 | SpringApplication.run(MainApplication.class, args); 53 | } 54 | 55 | } 56 | ``` 57 | 58 | 4、use dynamic sql 59 | 60 | 1)、define model 61 | ```java 62 | @Data 63 | @Table("t_user") 64 | public class User { 65 | 66 | @Id 67 | private Long id; 68 | 69 | @Column("nick") 70 | private String name; 71 | 72 | @Embedded.Empty 73 | private Address address; 74 | 75 | @CreatedDate 76 | @Column("create_date") 77 | private LocalDateTime created; 78 | 79 | @LastModifiedDate 80 | @Column("last_modified_date") 81 | private LocalDateTime modified; 82 | 83 | @Data 84 | public static class Address { 85 | private String province; 86 | private String city; 87 | private String area; 88 | } 89 | 90 | } 91 | ``` 92 | 2)、Dao interface 93 | ```java 94 | public interface UserDao extends ListCrudRepository, 95 | CriteriaExecutor, JdbcSupport { 96 | 97 | /** 98 | * Criteria example 99 | */ 100 | default Page searchByQuery(UserQuery query, Pageable pageable) { 101 | return findAll(Criteria.from(MoreCriteria.eq(User_.province, query.province)) 102 | .and(MoreCriteria.eq(User_.city, query.city)) 103 | .and(MoreCriteria.like(User_.area, query.area)) 104 | .and(MoreCriteria.like(User_.name, query.nick)) 105 | .and(MoreCriteria.between(User_.created, query.createFrom, query.createTo)) 106 | , pageable); 107 | } 108 | 109 | /** 110 | * Jdbc support example 111 | */ 112 | default List searchByQuery(UserQuery query) { 113 | return namedJdbcTemplate().queryForList( 114 | "select * " + 115 | "from t_user " + 116 | "where 1=1 " + 117 | (query.province == null ? "" : "and province=:province ") + 118 | (query.city == null ? "" : "and city=:city ") + 119 | (query.area == null ? "" : "and area=:area ") + 120 | (query.nick == null ? "" : "and nick=:nick ") 121 | , new BeanPropertySqlParameterSource(query), User.class); 122 | } 123 | 124 | @Data 125 | class UserQuery { 126 | String nick; 127 | String province; 128 | String city; 129 | String area; 130 | LocalDateTime createFrom; 131 | LocalDateTime createTo; 132 | } 133 | } 134 | ``` 135 | 3)、use Dao 136 | ```java 137 | @RestController 138 | @AllArgsConstructor(onConstructor_ = @Autowired) 139 | public class UserController { 140 | 141 | UserDao userDao; 142 | 143 | @GetMapping("/search") 144 | public Page search(UserDao.UserQuery query, Pageable pageable) { 145 | return userDao.searchByQuery(query, pageable); 146 | } 147 | 148 | } 149 | ``` 150 | 151 | The complete example is [here](../spring-data-criteria-example/spring-data-criteria-jdbc-example). 152 | 153 | If you think it's good, please give this project a star. 154 | -------------------------------------------------------------------------------- /spring-data-criteria-jdbc/src/main/java/io/github/holmofy/data/jdbc/CriteriaExecutor.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jdbc; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.data.relational.core.query.CriteriaDefinition; 6 | 7 | import java.util.Optional; 8 | 9 | /** 10 | * Support Criteria queries 11 | * 12 | * @param Domain Class 13 | */ 14 | public interface CriteriaExecutor { 15 | 16 | Optional findOne(CriteriaDefinition criteria); 17 | 18 | Iterable findAll(CriteriaDefinition criteria); 19 | 20 | Page findAll(CriteriaDefinition criteria, Pageable pageable); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /spring-data-criteria-jdbc/src/main/java/io/github/holmofy/data/jdbc/EnhancedJdbcRepository.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jdbc; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.data.jdbc.core.JdbcAggregateOperations; 6 | import org.springframework.data.jdbc.core.convert.JdbcConverter; 7 | import org.springframework.data.jdbc.repository.support.SimpleJdbcRepository; 8 | import org.springframework.data.mapping.PersistentEntity; 9 | import org.springframework.data.relational.core.query.CriteriaDefinition; 10 | import org.springframework.data.relational.core.query.Query; 11 | 12 | import java.util.Optional; 13 | 14 | public class EnhancedJdbcRepository extends SimpleJdbcRepository implements CriteriaExecutor { 15 | 16 | private final JdbcAggregateOperations entityOperations; 17 | private final PersistentEntity entity; 18 | 19 | public EnhancedJdbcRepository(JdbcAggregateOperations entityOperations, 20 | PersistentEntity entity, 21 | JdbcConverter converter) { 22 | super(entityOperations, entity, converter); 23 | this.entityOperations = entityOperations; 24 | this.entity = entity; 25 | } 26 | 27 | @Override 28 | public Optional findOne(CriteriaDefinition criteria) { 29 | return entityOperations.findOne(Query.query(criteria), entity.getType()); 30 | } 31 | 32 | @Override 33 | public Iterable findAll(CriteriaDefinition criteria) { 34 | return entityOperations.findAll(Query.query(criteria), entity.getType()); 35 | } 36 | 37 | @Override 38 | public Page findAll(CriteriaDefinition criteria, Pageable pageable) { 39 | return entityOperations.findAll(Query.query(criteria), entity.getType(), pageable); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /spring-data-criteria-jdbc/src/main/java/io/github/holmofy/data/jdbc/JdbcSupport.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jdbc; 2 | 3 | import org.springframework.data.jdbc.core.JdbcAggregateOperations; 4 | import org.springframework.jdbc.core.JdbcOperations; 5 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; 6 | 7 | public interface JdbcSupport { 8 | 9 | JdbcOperations jdbcTemplate(); 10 | 11 | NamedParameterJdbcOperations namedJdbcTemplate(); 12 | 13 | JdbcAggregateOperations aggregateTemplate(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring-data-criteria-jdbc/src/main/java/io/github/holmofy/data/jdbc/JdbcSupportImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jdbc; 2 | 3 | import org.springframework.data.jdbc.core.JdbcAggregateOperations; 4 | import org.springframework.data.jdbc.core.JdbcAggregateTemplate; 5 | import org.springframework.jdbc.core.JdbcOperations; 6 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; 7 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; 8 | import org.springframework.stereotype.Repository; 9 | 10 | @Repository 11 | public class JdbcSupportImpl implements JdbcSupport { 12 | 13 | private final NamedParameterJdbcTemplate namedParameterJdbcTemplate; 14 | private final JdbcAggregateTemplate jdbcAggregateTemplate; 15 | 16 | public JdbcSupportImpl(NamedParameterJdbcTemplate namedParameterJdbcTemplate, 17 | JdbcAggregateTemplate jdbcAggregateTemplate) { 18 | this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; 19 | this.jdbcAggregateTemplate = jdbcAggregateTemplate; 20 | } 21 | 22 | @Override 23 | public JdbcOperations jdbcTemplate() { 24 | return namedParameterJdbcTemplate.getJdbcOperations(); 25 | } 26 | 27 | @Override 28 | public NamedParameterJdbcOperations namedJdbcTemplate() { 29 | return namedParameterJdbcTemplate; 30 | } 31 | 32 | @Override 33 | public JdbcAggregateOperations aggregateTemplate() { 34 | return jdbcAggregateTemplate; 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /spring-data-criteria-jpa/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-criteria 7 | io.github.holmofy 8 | ${reversion} 9 | 10 | 4.0.0 11 | 12 | spring-data-criteria-jpa 13 | 14 | 15 | 16 | org.springframework.data 17 | spring-data-jpa 18 | 19 | 20 | jakarta.persistence 21 | jakarta.persistence-api 22 | 23 | 24 | org.projectlombok 25 | lombok 26 | provided 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /spring-data-criteria-jpa/readme.md: -------------------------------------------------------------------------------- 1 | ## How to use 2 | 3 | 1、add dependency 4 | ```xml 5 | 6 | io.github.holmofy 7 | spring-data-criteria-jpa 8 | ${latest-version} 9 | 10 | ``` 11 | 12 | Find the latest version [here](https://repo1.maven.org/maven2/io/github/holmofy/spring-data-criteria-jpa) 13 | 14 | 2、add apt plugin: `hibernate-jpamodelgen` 15 | ```xml 16 | 17 | 18 | 19 | org.apache.maven.plugins 20 | maven-compiler-plugin 21 | ${maven-compiler-plugin.version} 22 | 23 | ${maven.compiler.source} 24 | ${maven.compiler.target} 25 | 26 | 27 | org.hibernate.orm 28 | hibernate-jpamodelgen 29 | 6.1.7.Final 30 | 31 | 32 | 33 | org.projectlombok 34 | lombok 35 | 1.18.24 36 | 37 | 38 | 39 | 40 | 41 | 42 | ``` 43 | 44 | 3、config Spring Data JPA 45 | 46 | ```java 47 | @EnableJpaAuditing 48 | @EnableJpaRepositories 49 | @SpringBootApplication 50 | public class MainApplication { 51 | 52 | public static void main(String[] args) { 53 | SpringApplication.run(MainApplication.class, args); 54 | } 55 | 56 | } 57 | ``` 58 | 59 | 4、use dynamic sql 60 | 61 | 1)、define model 62 | 63 | ```java 64 | @Data 65 | @Entity 66 | @Table(name = "t_user") 67 | @EntityListeners(AuditingEntityListener.class) 68 | public class User { 69 | 70 | @Id 71 | @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq") 72 | @SequenceGenerator(name = "user_seq", sequenceName = "t_user_seq", allocationSize = 1) 73 | private Long id; 74 | 75 | @Column(name = "nick") 76 | private String name; 77 | 78 | // NOTE: jpamodelgen currently does not support @Embedded 79 | private String province; 80 | private String city; 81 | private String area; 82 | 83 | @CreatedDate 84 | @Column(name = "created_date") 85 | private LocalDateTime created; 86 | 87 | @LastModifiedDate 88 | @Column(name = "last_modified_date") 89 | private LocalDateTime modified; 90 | 91 | 92 | } 93 | ``` 94 | 2)、Dao interface 95 | ```java 96 | public interface UserDao extends JpaRepository, JpaSpecificationExecutor { 97 | 98 | default Page searchByQuery(UserQuery query, Pageable pageable) { 99 | return findAll(Specification.where(MoreCriteria.eq(User_.province, query.province)) 100 | .and(MoreCriteria.eq(User_.city, query.city)) 101 | .and(MoreCriteria.like(User_.area, query.area)) 102 | .and(MoreCriteria.like(User_.name, query.nick)) 103 | .and(MoreCriteria.between(User_.created, query.createFrom, query.createTo)) 104 | , pageable); 105 | } 106 | 107 | @Data 108 | class UserQuery { 109 | String nick; 110 | String province; 111 | String city; 112 | String area; 113 | LocalDateTime createFrom; 114 | LocalDateTime createTo; 115 | } 116 | 117 | } 118 | ``` 119 | 3)、use Dao 120 | ```java 121 | @RestController 122 | public class UserController { 123 | 124 | @Autowired 125 | UserDao userDao; 126 | 127 | @GetMapping("/search") 128 | public Page search(UserDao.UserQuery query, Pageable pageable) { 129 | return userDao.searchByQuery(query, pageable); 130 | } 131 | 132 | } 133 | ``` 134 | 135 | The complete example is [here](../spring-data-criteria-example/spring-data-criteria-jpa-example). 136 | 137 | If you think it's good, please give this project a star. 138 | -------------------------------------------------------------------------------- /spring-data-criteria-jpa/src/main/java/io/github/holmofy/data/jpa/MoreCriteria.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.jpa; 2 | 3 | import jakarta.persistence.metamodel.SingularAttribute; 4 | import lombok.experimental.UtilityClass; 5 | import org.springframework.data.jpa.domain.Specification; 6 | import org.springframework.lang.Nullable; 7 | 8 | import java.util.Collection; 9 | 10 | @UtilityClass 11 | public class MoreCriteria { 12 | 13 | public static Specification alwaysTrue() { 14 | return (root, query, cb) -> cb.isTrue(cb.literal(Boolean.TRUE)); 15 | } 16 | 17 | public static Specification alwaysFalse() { 18 | return (root, query, cb) -> cb.isTrue(cb.literal(Boolean.FALSE)); 19 | } 20 | 21 | public static Specification isNull(SingularAttribute attr) { 22 | return (root, query, cb) -> cb.isNull(root.get(attr)); 23 | } 24 | 25 | public static Specification isNotNull(SingularAttribute attr) { 26 | return (root, query, cb) -> cb.isNotNull(root.get(attr)); 27 | } 28 | 29 | @Nullable 30 | public static Specification eq(SingularAttribute attr, Object value) { 31 | return isNullOrEmpty(value) ? null : (root, query, cb) -> cb.equal(root.get(attr), value); 32 | } 33 | 34 | @Nullable 35 | public static Specification notEq(SingularAttribute attr, Object value) { 36 | return isNullOrEmpty(value) ? null : (root, query, cb) -> cb.notEqual(root.get(attr), value); 37 | } 38 | 39 | @Nullable 40 | public static > Specification lt(SingularAttribute attr, Y value) { 41 | return isNullOrEmpty(value) ? null : (root, query, cb) -> cb.lessThan(root.get(attr), value); 42 | } 43 | 44 | @Nullable 45 | public static > Specification lte(SingularAttribute attr, Y value) { 46 | return isNullOrEmpty(value) ? null : (root, query, cb) -> cb.lessThanOrEqualTo(root.get(attr), value); 47 | } 48 | 49 | @Nullable 50 | public static > Specification gt(SingularAttribute attr, Y value) { 51 | return isNullOrEmpty(value) ? null : (root, query, cb) -> cb.greaterThan(root.get(attr), value); 52 | } 53 | 54 | @Nullable 55 | public static > Specification gte(SingularAttribute attr, Y value) { 56 | return isNullOrEmpty(value) ? null : (root, query, cb) -> cb.greaterThanOrEqualTo(root.get(attr), value); 57 | } 58 | 59 | @Nullable 60 | public static > Specification between(SingularAttribute attr, Y begin, Y end) { 61 | if (begin == null && end == null) { 62 | return null; 63 | } 64 | if (begin != null && end != null) { 65 | return (root, query, cb) -> cb.between(root.get(attr), begin, end); 66 | } 67 | return begin == null ? lte(attr, end) : gte(attr, begin); 68 | } 69 | 70 | @Nullable 71 | public static Specification like(SingularAttribute attr, String value) { 72 | return isNullOrEmpty(value) ? null : (root, query, cb) -> cb.like(root.get(attr), value); 73 | } 74 | 75 | @Nullable 76 | public static Specification startWith(SingularAttribute attr, String value) { 77 | return isNullOrEmpty(value) ? null : (root, query, cb) -> cb.like(root.get(attr), escapeLikeClause(value) + "%"); 78 | } 79 | 80 | @Nullable 81 | public static Specification in(SingularAttribute attr, Collection values) { 82 | return isNullOrEmpty(values) ? null : (root, query, cb) -> cb.isTrue(root.get(attr).in(values)); 83 | } 84 | 85 | @Nullable 86 | public static Specification notIn(SingularAttribute attr, Collection values) { 87 | return isNullOrEmpty(values) ? null : (root, query, cb) -> cb.isTrue(root.get(attr).in(values).not()); 88 | } 89 | 90 | public static boolean isNullOrEmpty(Collection collection) { 91 | return collection == null || collection.isEmpty(); 92 | } 93 | 94 | public static boolean isNullOrEmpty(Object obj) { 95 | return obj == null || obj instanceof String && ((String) obj).isEmpty(); 96 | } 97 | 98 | private static String escapeLikeClause(CharSequence expression) { 99 | return expression.toString().replace("%", "\\%").replace("_", "\\_"); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /spring-data-criteria-r2dbc/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-criteria 7 | io.github.holmofy 8 | ${reversion} 9 | 10 | 4.0.0 11 | 12 | spring-data-criteria-r2dbc 13 | 14 | 15 | 16 | org.springframework.data 17 | spring-data-relational 18 | 19 | 20 | org.springframework.data 21 | spring-data-r2dbc 22 | 23 | 24 | io.github.holmofy 25 | spring-data-criteria-relational 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /spring-data-criteria-r2dbc/readme.md: -------------------------------------------------------------------------------- 1 | ## How to use 2 | 3 | 1、add dependency 4 | ```xml 5 | 6 | io.github.holmofy 7 | spring-data-criteria-r2dbc 8 | ${latest-version} 9 | 10 | ``` 11 | 12 | Find the latest version [here](https://repo1.maven.org/maven2/io/github/holmofy/spring-data-criteria-r2dbc) 13 | 14 | 2、add apt plugin. It is like `hibernate-jpamodelgen`, which will help you generate corresponding mapping fields according to the model of SpringData 15 | ```xml 16 | 17 | 18 | 19 | org.apache.maven.plugins 20 | maven-compiler-plugin 21 | ${maven-compiler-plugin.version} 22 | 23 | ${maven.compiler.source} 24 | ${maven.compiler.target} 25 | 26 | 27 | io.github.holmofy 28 | spring-data-criteria-apt 29 | ${latest-version} 30 | 31 | 32 | 33 | org.projectlombok 34 | lombok 35 | 1.18.24 36 | 37 | 38 | 39 | 40 | 41 | 42 | ``` 43 | 44 | 3、config Spring Data R2DBC: `@EnableR2dbcRepositories(repositoryBaseClass = EnhancedR2dbcRepository.class)` 45 | 46 | ```java 47 | @SpringBootApplication 48 | @EnableR2dbcRepositories(repositoryBaseClass = EnhancedR2dbcRepository.class) 49 | public class MainApplication { 50 | 51 | public static void main(String[] args) { 52 | SpringApplication.run(MainApplication.class, args); 53 | } 54 | 55 | // Webflux does not support Pageable by default, so we need to manually register it. 56 | @Bean 57 | WebFluxConfigurer springDataArgumentResolversConfigurer() { 58 | return new WebFluxConfigurer() { 59 | 60 | @Override 61 | public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) { 62 | configurer.addCustomResolver(new ReactiveSortHandlerMethodArgumentResolver(), 63 | new ReactivePageableHandlerMethodArgumentResolver()); 64 | } 65 | }; 66 | } 67 | 68 | } 69 | ``` 70 | 71 | **NOTE: These two issues [spring-data-commons/issues/1846](https://github.com/spring-projects/spring-data-commons/issues/1846) & [spring-boot/issues/20701](https://github.com/spring-projects/spring-boot/issues/20701) can track the progress of WebFlux's support for `Pageable`** 72 | 73 | 4、use dynamic sql 74 | 75 | 1)、define model 76 | 77 | **NOTE: spring-data-r2dbc currently does not support @Embedded to see [spring-data-r2dbc/issues/288](https://github.com/spring-projects/spring-data-r2dbc/issues/288)** 78 | 79 | ```java 80 | @Data 81 | @Table("t_user") 82 | public class User { 83 | 84 | @Id 85 | private Long id; 86 | 87 | @Column("nick") 88 | private String name; 89 | 90 | // NOTE: spring-data-r2dbc currently does not support @Embedded 91 | @Embedded.Empty 92 | private Address address; 93 | 94 | @CreatedDate 95 | @Column("create_date") 96 | private LocalDateTime created; 97 | 98 | @LastModifiedDate 99 | @Column("last_modified_date") 100 | private LocalDateTime modified; 101 | 102 | @Data 103 | public static class Address { 104 | private String province; 105 | private String city; 106 | private String area; 107 | } 108 | 109 | } 110 | ``` 111 | 2)、Dao interface 112 | ```java 113 | public interface UserDao extends ListCrudRepository, 114 | CriteriaExecutor, JdbcSupport { 115 | 116 | /** 117 | * Criteria example 118 | */ 119 | default Page searchByQuery(UserQuery query, Pageable pageable) { 120 | return findAll(Criteria.from(MoreCriteria.eq(User_.province, query.province)) 121 | .and(MoreCriteria.eq(User_.city, query.city)) 122 | .and(MoreCriteria.like(User_.area, query.area)) 123 | .and(MoreCriteria.like(User_.name, query.nick)) 124 | .and(MoreCriteria.between(User_.created, query.createFrom, query.createTo)) 125 | , pageable); 126 | } 127 | 128 | @Data 129 | class UserQuery { 130 | String nick; 131 | String province; 132 | String city; 133 | String area; 134 | LocalDateTime createFrom; 135 | LocalDateTime createTo; 136 | } 137 | } 138 | ``` 139 | 3)、use Dao 140 | ```java 141 | @RestController 142 | @AllArgsConstructor(onConstructor_ = @Autowired) 143 | public class UserController { 144 | 145 | UserDao userDao; 146 | 147 | @GetMapping("/search") 148 | public Memo> search(UserDao.UserQuery query, Pageable pageable) { 149 | return userDao.searchByQuery(query, pageable); 150 | } 151 | 152 | } 153 | ``` 154 | 155 | The complete example is [here](../spring-data-criteria-example/spring-data-criteria-r2dbc-example). 156 | 157 | If you think it's good, please give this project a star. 158 | -------------------------------------------------------------------------------- /spring-data-criteria-r2dbc/src/main/java/io/github/holmofy/data/r2dbc/CriteriaExecutor.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.r2dbc; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.data.r2dbc.core.R2dbcEntityTemplate; 6 | import org.springframework.data.relational.core.query.CriteriaDefinition; 7 | import org.springframework.data.relational.core.query.Query; 8 | import reactor.core.publisher.Flux; 9 | import reactor.core.publisher.Mono; 10 | 11 | /** 12 | * Support Criteria queries 13 | * 14 | * @param Domain Class 15 | */ 16 | public interface CriteriaExecutor { 17 | 18 | /** 19 | * @see R2dbcEntityTemplate#selectOne(Query, Class) 20 | */ 21 | Mono findOne(CriteriaDefinition criteria); 22 | 23 | /** 24 | * @see R2dbcEntityTemplate#select(Query, Class) 25 | */ 26 | Flux findAll(CriteriaDefinition criteria); 27 | 28 | /** 29 | * @see R2dbcEntityTemplate#select(Class) 30 | */ 31 |

Mono

findOne(CriteriaDefinition criteria, Class

projection); 32 | 33 | /** 34 | * @see R2dbcEntityTemplate#select(Class) 35 | */ 36 |

Flux

findAll(CriteriaDefinition criteria, Class

projection); 37 | 38 | /** 39 | * @see R2dbcEntityTemplate#count(Query, Class) 40 | */ 41 | Mono count(CriteriaDefinition criteria); 42 | 43 | /** 44 | * @see R2dbcEntityTemplate#select(Query, Class) 45 | */ 46 | Mono> findAll(CriteriaDefinition criteria, Pageable pageable); 47 | 48 | /** 49 | * @see R2dbcEntityTemplate#select(Query, Class) 50 | */ 51 |

Mono> findAll(CriteriaDefinition criteria, Pageable pageable, Class

projection); 52 | 53 | } 54 | -------------------------------------------------------------------------------- /spring-data-criteria-r2dbc/src/main/java/io/github/holmofy/data/r2dbc/EnhancedR2dbcRepository.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.r2dbc; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.PageImpl; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.r2dbc.convert.R2dbcConverter; 7 | import org.springframework.data.r2dbc.core.R2dbcEntityOperations; 8 | import org.springframework.data.r2dbc.core.R2dbcEntityTemplate; 9 | import org.springframework.data.r2dbc.core.ReactiveDataAccessStrategy; 10 | import org.springframework.data.r2dbc.repository.support.SimpleR2dbcRepository; 11 | import org.springframework.data.relational.core.query.CriteriaDefinition; 12 | import org.springframework.data.relational.core.query.Query; 13 | import org.springframework.data.relational.repository.query.RelationalEntityInformation; 14 | import org.springframework.r2dbc.core.DatabaseClient; 15 | import reactor.core.publisher.Flux; 16 | import reactor.core.publisher.Mono; 17 | 18 | import java.util.List; 19 | 20 | public class EnhancedR2dbcRepository extends SimpleR2dbcRepository implements CriteriaExecutor, R2dbcSupport { 21 | 22 | private final RelationalEntityInformation entity; 23 | private final R2dbcEntityOperations entityOperations; 24 | 25 | public EnhancedR2dbcRepository(RelationalEntityInformation entity, 26 | R2dbcEntityOperations entityOperations, 27 | R2dbcConverter converter) { 28 | super(entity, entityOperations, converter); 29 | this.entity = entity; 30 | this.entityOperations = entityOperations; 31 | } 32 | 33 | public EnhancedR2dbcRepository(RelationalEntityInformation entity, 34 | DatabaseClient databaseClient, 35 | R2dbcConverter converter, 36 | ReactiveDataAccessStrategy accessStrategy) { 37 | this(entity, new R2dbcEntityTemplate(databaseClient, accessStrategy), converter); 38 | } 39 | 40 | @Override 41 | public Mono findOne(CriteriaDefinition criteria) { 42 | return entityOperations.selectOne(Query.query(criteria), entity.getJavaType()); 43 | } 44 | 45 | @Override 46 | public Flux findAll(CriteriaDefinition criteria) { 47 | return entityOperations.select(Query.query(criteria), entity.getJavaType()); 48 | } 49 | 50 | @Override 51 | public

Mono

findOne(CriteriaDefinition criteria, Class

projection) { 52 | return entityOperations.select(entity.getJavaType()) 53 | .from(entity.getTableName()) 54 | .as(projection) 55 | .matching(Query.query(criteria)) 56 | .one(); 57 | } 58 | 59 | @Override 60 | public

Flux

findAll(CriteriaDefinition criteria, Class

projection) { 61 | return entityOperations.select(entity.getJavaType()) 62 | .from(entity.getTableName()) 63 | .as(projection) 64 | .matching(Query.query(criteria)) 65 | .all(); 66 | } 67 | 68 | @Override 69 | public Mono count(CriteriaDefinition criteria) { 70 | return entityOperations.count(Query.query(criteria), entity.getJavaType()); 71 | } 72 | 73 | @Override 74 | public Mono> findAll(CriteriaDefinition criteria, Pageable pageable) { 75 | Query query = Query.query(criteria); 76 | Mono count = entityOperations.count(query, entity.getJavaType()); 77 | Mono> list = entityOperations.select(query.with(pageable), entity.getJavaType()) 78 | .collectList(); 79 | return Mono.zip(list, count).map(tuple -> new PageImpl<>(tuple.getT1(), pageable, tuple.getT2())); 80 | } 81 | 82 | @Override 83 | public

Mono> findAll(CriteriaDefinition criteria, Pageable pageable, Class

projection) { 84 | Query query = Query.query(criteria); 85 | Mono count = entityOperations.count(query, entity.getJavaType()); 86 | Mono> list = entityOperations.select(entity.getJavaType()) 87 | .from(entity.getTableName()) 88 | .as(projection) 89 | .matching(query.with(pageable)) 90 | .all() 91 | .collectList(); 92 | return Mono.zip(list, count).map(tuple -> new PageImpl<>(tuple.getT1(), pageable, tuple.getT2())); 93 | } 94 | 95 | @Override 96 | public R2dbcEntityOperations r2dbcTemplate() { 97 | return entityOperations; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /spring-data-criteria-r2dbc/src/main/java/io/github/holmofy/data/r2dbc/R2dbcSupport.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.r2dbc; 2 | 3 | import org.springframework.data.r2dbc.core.R2dbcEntityOperations; 4 | import org.springframework.data.r2dbc.core.R2dbcEntityTemplate; 5 | 6 | public interface R2dbcSupport { 7 | 8 | /** 9 | * @return R2dbcEntityTemplate 10 | * @see R2dbcEntityTemplate 11 | */ 12 | R2dbcEntityOperations r2dbcTemplate(); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /spring-data-criteria-relational/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-criteria 7 | io.github.holmofy 8 | ${reversion} 9 | 10 | 4.0.0 11 | 12 | spring-data-criteria-relational 13 | 14 | 15 | 16 | org.springframework.data 17 | spring-data-relational 18 | 19 | 20 | org.projectlombok 21 | lombok 22 | provided 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /spring-data-criteria-relational/src/main/java/io/github/holmofy/data/relational/MoreCriteria.java: -------------------------------------------------------------------------------- 1 | package io.github.holmofy.data.relational; 2 | 3 | import lombok.experimental.UtilityClass; 4 | import org.springframework.data.relational.core.query.Criteria; 5 | import org.springframework.util.CollectionUtils; 6 | 7 | import java.util.Arrays; 8 | import java.util.Collection; 9 | 10 | @UtilityClass 11 | public class MoreCriteria { 12 | 13 | public static Criteria isNull(String column) { 14 | return Criteria.where(column).isNull(); 15 | } 16 | 17 | public static Criteria isNotNull(String column) { 18 | return Criteria.where(column).isNotNull(); 19 | } 20 | 21 | public static Criteria eq(String column, T obj) { 22 | return obj == null ? Criteria.empty() : Criteria.where(column).is(obj); 23 | } 24 | 25 | public static Criteria lt(String column, T obj) { 26 | return obj == null ? Criteria.empty() : Criteria.where(column).lessThan(obj); 27 | } 28 | 29 | public static Criteria lte(String column, T obj) { 30 | return obj == null ? Criteria.empty() : Criteria.where(column).lessThanOrEquals(obj); 31 | } 32 | 33 | public static Criteria gt(String column, T obj) { 34 | return obj == null ? Criteria.empty() : Criteria.where(column).greaterThan(obj); 35 | } 36 | 37 | public static Criteria gte(String column, T obj) { 38 | return obj == null ? Criteria.empty() : Criteria.where(column).greaterThanOrEquals(obj); 39 | } 40 | 41 | public static Criteria between(String column, T begin, T end) { 42 | if (begin == null && end == null) { 43 | return Criteria.empty(); 44 | } 45 | if (begin != null && end != null) { 46 | return Criteria.where(column).between(begin, end); 47 | } 48 | return begin == null ? lte(column, end) : gte(column, begin); 49 | } 50 | 51 | public static Criteria like(String column, T obj) { 52 | return obj == null || obj.length() == 0 ? Criteria.empty() : Criteria.where(column).like(obj); 53 | } 54 | 55 | public static Criteria startWith(String column, T obj) { 56 | return obj == null || obj.length() == 0 ? Criteria.empty() : Criteria.where(column).like(escapeLikeClause(obj) + "%"); 57 | } 58 | 59 | @SafeVarargs 60 | public static Criteria in(String column, T... objs) { 61 | return objs == null ? Criteria.empty() : Criteria.where(column).in(Arrays.asList(objs)); 62 | } 63 | 64 | @SafeVarargs 65 | public static Criteria notIn(String column, T... objs) { 66 | return objs == null ? Criteria.empty() : Criteria.where(column).notIn(Arrays.asList(objs)); 67 | } 68 | 69 | public static Criteria in(String column, Collection collection) { 70 | return CollectionUtils.isEmpty(collection) ? Criteria.empty() : Criteria.where(column).in(collection); 71 | } 72 | 73 | public static Criteria notIn(String column, Collection collection) { 74 | return CollectionUtils.isEmpty(collection) ? Criteria.empty() : Criteria.where(column).notIn(collection); 75 | } 76 | 77 | private static String escapeLikeClause(CharSequence expression) { 78 | return expression.toString().replace("%", "\\%").replace("_", "\\_"); 79 | } 80 | 81 | } 82 | --------------------------------------------------------------------------------