IGNITE-6879 Support Spring Data 2.0 - Fixes #3704. Signed-off-by: dpavlov <[email protected]>
Project: http://git-wip-us.apache.org/repos/asf/ignite/repo Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/22040a3c Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/22040a3c Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/22040a3c Branch: refs/heads/master Commit: 22040a3cb2691d6afe3893208243ca6e1b29f99d Parents: 666f220 Author: Roman_Meerson <[email protected]> Authored: Tue May 8 18:38:01 2018 +0300 Committer: dpavlov <[email protected]> Committed: Tue May 8 18:38:01 2018 +0300 ---------------------------------------------------------------------- examples/pom.xml | 2 +- .../examples/springdata/PersonRepository.java | 6 +- .../examples/springdata/SpringAppCfg.java | 6 +- .../examples/springdata/SpringDataExample.java | 4 +- modules/spring-data-2.0/README.txt | 32 ++ modules/spring-data-2.0/licenses/apache-2.0.txt | 202 ++++++++++++ modules/spring-data-2.0/pom.xml | 85 +++++ .../repository/IgniteRepository.java | 58 ++++ .../config/EnableIgniteRepositories.java | 119 +++++++ .../config/IgniteRepositoriesRegistar.java | 36 +++ .../IgniteRepositoryConfigurationExtension.java | 49 +++ .../springdata20/repository/config/Query.java | 37 +++ .../repository/config/RepositoryConfig.java | 39 +++ .../repository/config/package-info.java | 22 ++ .../springdata20/repository/package-info.java | 22 ++ .../repository/query/IgniteQuery.java | 82 +++++ .../repository/query/IgniteQueryGenerator.java | 246 +++++++++++++++ .../repository/query/IgniteRepositoryQuery.java | 311 +++++++++++++++++++ .../repository/query/package-info.java | 22 ++ .../repository/support/ConditionFalse.java | 33 ++ .../support/IgniteRepositoryFactory.java | 156 ++++++++++ .../support/IgniteRepositoryFactoryBean.java | 91 ++++++ .../support/IgniteRepositoryImpl.java | 164 ++++++++++ .../repository/support/package-info.java | 22 ++ .../IgniteSpringDataCrudSelfTest.java | 234 ++++++++++++++ .../IgniteSpringDataQueriesSelfTest.java | 299 ++++++++++++++++++ .../misc/ApplicationConfiguration.java | 58 ++++ .../apache/ignite/springdata/misc/Person.java | 98 ++++++ .../springdata/misc/PersonRepository.java | 91 ++++++ .../springdata/misc/PersonSecondRepository.java | 40 +++ .../testsuites/IgniteSpringData2TestSuite.java | 40 +++ parent/pom.xml | 3 +- pom.xml | 1 + 33 files changed, 2700 insertions(+), 10 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/examples/pom.xml ---------------------------------------------------------------------- diff --git a/examples/pom.xml b/examples/pom.xml index cab1a89..872f52b 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -67,7 +67,7 @@ <dependency> <groupId>org.apache.ignite</groupId> - <artifactId>ignite-spring-data</artifactId> + <artifactId>ignite-spring-data_2.0</artifactId> <version>${project.version}</version> </dependency> http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/examples/src/main/java/org/apache/ignite/examples/springdata/PersonRepository.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java/org/apache/ignite/examples/springdata/PersonRepository.java b/examples/src/main/java/org/apache/ignite/examples/springdata/PersonRepository.java index 0517311..f401ab2 100644 --- a/examples/src/main/java/org/apache/ignite/examples/springdata/PersonRepository.java +++ b/examples/src/main/java/org/apache/ignite/examples/springdata/PersonRepository.java @@ -20,9 +20,9 @@ package org.apache.ignite.examples.springdata; import java.util.List; import javax.cache.Cache; import org.apache.ignite.examples.model.Person; -import org.apache.ignite.springdata.repository.IgniteRepository; -import org.apache.ignite.springdata.repository.config.Query; -import org.apache.ignite.springdata.repository.config.RepositoryConfig; +import org.apache.ignite.springdata20.repository.IgniteRepository; +import org.apache.ignite.springdata20.repository.config.Query; +import org.apache.ignite.springdata20.repository.config.RepositoryConfig; import org.springframework.data.domain.Pageable; /** http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/examples/src/main/java/org/apache/ignite/examples/springdata/SpringAppCfg.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java/org/apache/ignite/examples/springdata/SpringAppCfg.java b/examples/src/main/java/org/apache/ignite/examples/springdata/SpringAppCfg.java index 0dcf5d6..78f2085 100644 --- a/examples/src/main/java/org/apache/ignite/examples/springdata/SpringAppCfg.java +++ b/examples/src/main/java/org/apache/ignite/examples/springdata/SpringAppCfg.java @@ -22,9 +22,9 @@ import org.apache.ignite.Ignition; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.examples.model.Person; -import org.apache.ignite.springdata.repository.IgniteRepository; -import org.apache.ignite.springdata.repository.config.EnableIgniteRepositories; -import org.apache.ignite.springdata.repository.support.IgniteRepositoryFactoryBean; +import org.apache.ignite.springdata20.repository.IgniteRepository; +import org.apache.ignite.springdata20.repository.config.EnableIgniteRepositories; +import org.apache.ignite.springdata20.repository.support.IgniteRepositoryFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/examples/src/main/java/org/apache/ignite/examples/springdata/SpringDataExample.java ---------------------------------------------------------------------- diff --git a/examples/src/main/java/org/apache/ignite/examples/springdata/SpringDataExample.java b/examples/src/main/java/org/apache/ignite/examples/springdata/SpringDataExample.java index 6233698..bbf6ab7 100644 --- a/examples/src/main/java/org/apache/ignite/examples/springdata/SpringDataExample.java +++ b/examples/src/main/java/org/apache/ignite/examples/springdata/SpringDataExample.java @@ -108,7 +108,7 @@ public class SpringDataExample { */ private static void findPersons() { // Getting Person with specific ID. - Person person = repo.findOne(2L); + Person person = repo.findById(2L).orElse(null); System.out.println("\n>>> Found Person [id=" + 2L + ", val=" + person + "]"); @@ -119,7 +119,7 @@ public class SpringDataExample { for (long i = 0; i < 5; i++) ids.add(i); - Iterator<Person> persons = repo.findAll(ids).iterator(); + Iterator<Person> persons = repo.findAllById(ids).iterator(); System.out.println("\n>>> Persons list for specific ids: "); http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/README.txt ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/README.txt b/modules/spring-data-2.0/README.txt new file mode 100644 index 0000000..f74d97a --- /dev/null +++ b/modules/spring-data-2.0/README.txt @@ -0,0 +1,32 @@ +Apache Ignite Spring Module +--------------------------- + +Apache Ignite Spring Data 2.0 module provides an integration with Spring Data 2.0 framework. + +To enable Spring Data 2.0 module when starting a standalone node, move 'optional/ignite-spring-data' folder to +'libs' folder before running 'ignite.{sh|bat}' script. The content of the module folder will +be added to classpath in this case. + +Importing Spring Data 2.0 Module In Maven Project +---------------------------------------- + +If you are using Maven to manage dependencies of your project, you can add Spring module +dependency like this (replace '${ignite.version}' with actual Ignite version you are +interested in): + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 + http://maven.apache.org/xsd/maven-4.0.0.xsd"> + ... + <dependencies> + ... + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-spring-data_2.0</artifactId> + <version>${ignite.version}</version> + </dependency> + ... + </dependencies> + ... +</project> http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/licenses/apache-2.0.txt ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/licenses/apache-2.0.txt b/modules/spring-data-2.0/licenses/apache-2.0.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/modules/spring-data-2.0/licenses/apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/pom.xml ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/pom.xml b/modules/spring-data-2.0/pom.xml new file mode 100644 index 0000000..dc56fcb --- /dev/null +++ b/modules/spring-data-2.0/pom.xml @@ -0,0 +1,85 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> + +<!-- + POM file. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-parent</artifactId> + <version>1</version> + <relativePath>../../parent</relativePath> + </parent> + + <artifactId>ignite-spring-data_2.0</artifactId> + <version>2.5.0-SNAPSHOT</version> + <url>http://ignite.apache.org</url> + + <dependencies> + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-core</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-indexing</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-log4j</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.springframework.data</groupId> + <artifactId>spring-data-commons</artifactId> + <version>${spring.data-2.0.version}</version> + <!-- Exclude slf4j logging in favor of log4j --> + <exclusions> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>jcl-over-slf4j</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-spring</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.ignite</groupId> + <artifactId>ignite-core</artifactId> + <version>${project.version}</version> + <type>test-jar</type> + <scope>test</scope> + </dependency> + </dependencies> + +</project> http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/IgniteRepository.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/IgniteRepository.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/IgniteRepository.java new file mode 100644 index 0000000..2e014f1 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/IgniteRepository.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.springdata20.repository; + +import java.io.Serializable; +import java.util.Map; +import org.springframework.data.repository.CrudRepository; + +/** + * Apache Ignite repository that extends basic capabilities of {@link CrudRepository}. + */ +public interface IgniteRepository<T, ID extends Serializable> extends CrudRepository<T, ID> { + /** + * Saves a given entity using provided key. + * </p> + * It's suggested to use this method instead of default {@link CrudRepository#save(Object)} that generates + * IDs (keys) that are not unique cluster wide. + * + * @param key Entity's key. + * @param entity Entity to save. + * @param <S> Entity type. + * @return Saved entity. + */ + <S extends T> S save(ID key, S entity); + + /** + * Saves all given keys and entities combinations. + * </p> + * It's suggested to use this method instead of default {@link CrudRepository#save(Object)} that generates + * IDs (keys) that are not unique cluster wide. + * + * @param entities Map of key-entities pairs to save. + * @param <S> type of entities. + * @return Saved entities. + */ + <S extends T> Iterable<S> save(Map<ID, S> entities); + + /** + * Deletes all the entities for the provided ids. + * + * @param ids List of ids to delete. + */ + void deleteAllById(Iterable<ID> ids); +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/EnableIgniteRepositories.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/EnableIgniteRepositories.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/EnableIgniteRepositories.java new file mode 100644 index 0000000..b1b6016 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/EnableIgniteRepositories.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.springdata20.repository.config; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import org.apache.ignite.springdata20.repository.support.IgniteRepositoryFactoryBean; +import org.apache.ignite.springdata20.repository.support.IgniteRepositoryImpl; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.context.annotation.ComponentScan.Filter; +import org.springframework.context.annotation.Import; +import org.springframework.data.repository.query.QueryLookupStrategy; +import org.springframework.data.repository.query.QueryLookupStrategy.Key; + +/** + * Annotation to activate Apache Ignite repositories. If no base package is configured through either {@link #value()}, + * {@link #basePackages()} or {@link #basePackageClasses()} it will trigger scanning of the package of annotated class. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +@Import(IgniteRepositoriesRegistar.class) +public @interface EnableIgniteRepositories { + /** + * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.: + * {@code @EnableIgniteRepositories("org.my.pkg")} instead of + * {@code @EnableIgniteRepositories(basePackages="org.my.pkg")}. + */ + String[] value() default {}; + + /** + * Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) + * this attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names. + */ + String[] basePackages() default {}; + + /** + * Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. + * The package of each class specified will be scanned. Consider creating a special no-op marker class or interface + * in each package that serves no purpose other than being referenced by this attribute. + */ + Class<?>[] basePackageClasses() default {}; + + /** + * Specifies which types are not eligible for component scanning. + */ + Filter[] excludeFilters() default {}; + + /** + * Specifies which types are eligible for component scanning. Further narrows the set of candidate components from + * everything in {@link #basePackages()} to everything in the base packages that matches the given filter or + * filters. + */ + Filter[] includeFilters() default {}; + + /** + * Returns the postfix to be used when looking up custom repository implementations. Defaults to {@literal Impl}. So + * for a repository named {@code PersonRepository} the corresponding implementation class will be looked up scanning + * for {@code PersonRepositoryImpl}. + * + * @return Postfix to be used when looking up custom repository implementations. + */ + String repositoryImplementationPostfix() default "Impl"; + + /** + * Configures the location of where to find the Spring Data named queries properties file. + * + * @return Location of where to find the Spring Data named queries properties file. + */ + String namedQueriesLocation() default ""; + + /** + * Returns the key of the {@link QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to + * {@link Key#CREATE_IF_NOT_FOUND}. + * + * @return Key of the {@link QueryLookupStrategy} to be used for lookup queries for query methods. + */ + Key queryLookupStrategy() default Key.CREATE_IF_NOT_FOUND; + + /** + * Returns the {@link FactoryBean} class to be used for each repository instance. Defaults to + * {@link IgniteRepositoryFactoryBean}. + * + * @return {@link FactoryBean} class to be used for each repository instance. + */ + Class<?> repositoryFactoryBeanClass() default IgniteRepositoryFactoryBean.class; + + /** + * Configure the repository base class to be used to create repository proxies for this particular configuration. + * + * @return Repository base class to be used to create repository proxies for this particular configuration. + */ + Class<?> repositoryBaseClass() default IgniteRepositoryImpl.class; + + /** + * Configures whether nested repository-interfaces (e.g. defined as inner classes) should be discovered by the + * repositories infrastructure. + */ + boolean considerNestedRepositories() default false; +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/IgniteRepositoriesRegistar.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/IgniteRepositoriesRegistar.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/IgniteRepositoriesRegistar.java new file mode 100644 index 0000000..83ff7ff --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/IgniteRepositoriesRegistar.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.springdata20.repository.config; + +import java.lang.annotation.Annotation; +import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport; +import org.springframework.data.repository.config.RepositoryConfigurationExtension; + +/** + * Apache Ignite specific implementation of {@link RepositoryBeanDefinitionRegistrarSupport}. + */ +public class IgniteRepositoriesRegistar extends RepositoryBeanDefinitionRegistrarSupport { + /** {@inheritDoc} */ + @Override protected Class<? extends Annotation> getAnnotation() { + return EnableIgniteRepositories.class; + } + + /** {@inheritDoc} */ + @Override protected RepositoryConfigurationExtension getExtension() { + return new IgniteRepositoryConfigurationExtension(); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/IgniteRepositoryConfigurationExtension.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/IgniteRepositoryConfigurationExtension.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/IgniteRepositoryConfigurationExtension.java new file mode 100644 index 0000000..d770084 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/IgniteRepositoryConfigurationExtension.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.springdata20.repository.config; + +import java.util.Collection; +import java.util.Collections; +import org.apache.ignite.springdata20.repository.IgniteRepository; +import org.apache.ignite.springdata20.repository.support.IgniteRepositoryFactoryBean; +import org.springframework.data.repository.config.RepositoryConfigurationExtension; +import org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport; + +/** + * Apache Ignite specific implementation of {@link RepositoryConfigurationExtension}. + */ +public class IgniteRepositoryConfigurationExtension extends RepositoryConfigurationExtensionSupport { + /** {@inheritDoc} */ + @Override public String getModuleName() { + return "Apache Ignite"; + } + + /** {@inheritDoc} */ + @Override protected String getModulePrefix() { + return "ignite"; + } + + /** {@inheritDoc} */ + @Override public String getRepositoryFactoryBeanClassName() { + return IgniteRepositoryFactoryBean.class.getName(); + } + + /** {@inheritDoc} */ + @Override protected Collection<Class<?>> getIdentifyingTypes() { + return Collections.<Class<?>>singleton(IgniteRepository.class); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/Query.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/Query.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/Query.java new file mode 100644 index 0000000..936f336 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/Query.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.springdata20.repository.config; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation to provide a user defined SQL query for a method. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Query { + /** + * SQL query text string. + */ + String value() default ""; +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/RepositoryConfig.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/RepositoryConfig.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/RepositoryConfig.java new file mode 100644 index 0000000..79e60a8 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/RepositoryConfig.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.springdata20.repository.config; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The annotation can be used to pass Ignite specific parameters to a bound repository. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +public @interface RepositoryConfig { + /** + * @return A name of a distributed Apache Ignite cache an annotated repository will be mapped to. + */ + String cacheName() default ""; +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/package-info.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/package-info.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/package-info.java new file mode 100644 index 0000000..1c7b2f9 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/config/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * <!-- Package description. --> + * Package includes Spring Data integration related configuration files. + */ +package org.apache.ignite.springdata20.repository.config; http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/package-info.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/package-info.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/package-info.java new file mode 100644 index 0000000..9df5513 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * <!-- Package description. --> + * Package contains Apache Ignite Spring Data integration. + */ +package org.apache.ignite.springdata20.repository; http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteQuery.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteQuery.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteQuery.java new file mode 100644 index 0000000..7e626ae --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteQuery.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.springdata20.repository.query; + +/** + * Ignite query helper class. For internal use only. + */ +public class IgniteQuery { + /** */ + enum Option { + /** Query will be used with Sort object. */ + SORTING, + + /** Query will be used with Pageable object. */ + PAGINATION, + + /** No advanced option. */ + NONE + } + + /** Sql query text string. */ + private final String sql; + + /** */ + private final boolean isFieldQuery; + + /** Type of option. */ + private final Option option; + + /** + * @param sql Sql. + * @param isFieldQuery Is field query. + * @param option Option. + */ + public IgniteQuery(String sql, boolean isFieldQuery, Option option) { + this.sql = sql; + this.isFieldQuery = isFieldQuery; + this.option = option; + } + + /** + * Text string of the query. + * + * @return SQL query text string. + */ + public String sql() { + return sql; + } + + /** + * Returns {@code true} if it's Ignite SQL fields query, {@code false} otherwise. + * + * @return {@code true} if it's Ignite SQL fields query, {@code false} otherwise. + */ + public boolean isFieldQuery() { + return isFieldQuery; + } + + /** + * Advanced querying option. + * + * @return querying option. + */ + public Option options() { + return option; + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteQueryGenerator.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteQueryGenerator.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteQueryGenerator.java new file mode 100644 index 0000000..a8f5494 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteQueryGenerator.java @@ -0,0 +1,246 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.springdata20.repository.query; + +import java.lang.reflect.Method; +import org.jetbrains.annotations.NotNull; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.repository.core.RepositoryMetadata; +import org.springframework.data.repository.query.parser.Part; +import org.springframework.data.repository.query.parser.PartTree; + +/** + * Ignite query generator for Spring Data framework. + */ +public class IgniteQueryGenerator { + /** + * @param mtd Method. + * @param metadata Metadata. + * @return Generated ignite query. + */ + @NotNull public static IgniteQuery generateSql(Method mtd, RepositoryMetadata metadata) { + PartTree parts = new PartTree(mtd.getName(), metadata.getDomainType()); + + StringBuilder sql = new StringBuilder(); + + if (parts.isDelete()) + throw new UnsupportedOperationException("DELETE clause is not supported now."); + else { + sql.append("SELECT "); + + if (parts.isDistinct()) + throw new UnsupportedOperationException("DISTINCT clause in not supported."); + + if (parts.isCountProjection()) + sql.append("COUNT(1) "); + else + sql.append(" * "); + } + + sql.append("FROM ").append(metadata.getDomainType().getSimpleName()); + + if (parts.iterator().hasNext()) { + sql.append(" WHERE "); + + for (PartTree.OrPart orPart : parts) { + sql.append("("); + + for (Part part : orPart) { + handleQueryPart(sql, part); + sql.append(" AND "); + } + + sql.delete(sql.length() - 5, sql.length()); + + sql.append(") OR "); + } + + sql.delete(sql.length() - 4, sql.length()); + } + + addSorting(sql, parts.getSort()); + + if (parts.isLimiting()) { + sql.append(" LIMIT "); + sql.append(parts.getMaxResults().intValue()); + } + + return new IgniteQuery(sql.toString(), parts.isCountProjection(), getOptions(mtd)); + } + + /** + * Add a dynamic part of query for the sorting support. + * + * @param sql SQL text string. + * @param sort Sort method. + * @return Sorting criteria in StringBuilder. + */ + public static StringBuilder addSorting(StringBuilder sql, Sort sort) { + if (sort != null && sort != Sort.unsorted()) { + sql.append(" ORDER BY "); + + for (Sort.Order order : sort) { + sql.append(order.getProperty()).append(" ").append(order.getDirection()); + + if (order.getNullHandling() != Sort.NullHandling.NATIVE) { + sql.append(" ").append("NULL "); + + switch (order.getNullHandling()) { + case NULLS_FIRST: + sql.append("FIRST"); + break; + case NULLS_LAST: + sql.append("LAST"); + break; + } + } + sql.append(", "); + } + + sql.delete(sql.length() - 2, sql.length()); + } + + return sql; + } + + /** + * Add a dynamic part of a query for the pagination support. + * + * @param sql Builder instance. + * @param pageable Pageable instance. + * @return Builder instance. + */ + public static StringBuilder addPaging(StringBuilder sql, Pageable pageable) { + if (pageable.getSort() != null) + addSorting(sql, pageable.getSort()); + + sql.append(" LIMIT ").append(pageable.getPageSize()).append(" OFFSET ").append(pageable.getOffset()); + + return sql; + } + + /** + * Determines whether query is dynamic or not (by list of method parameters) + * + * @param mtd Method. + * @return type of options + */ + public static IgniteQuery.Option getOptions(Method mtd) { + IgniteQuery.Option option = IgniteQuery.Option.NONE; + + Class<?>[] types = mtd.getParameterTypes(); + if (types.length > 0) { + Class<?> type = types[types.length - 1]; + + if (Sort.class.isAssignableFrom(type)) + option = IgniteQuery.Option.SORTING; + else if (Pageable.class.isAssignableFrom(type)) + option = IgniteQuery.Option.PAGINATION; + } + + for (int i = 0; i < types.length - 1; i++) { + Class<?> tp = types[i]; + + if (tp == Sort.class || tp == Pageable.class) + throw new AssertionError("Sort and Pageable parameters are allowed only in the last position"); + } + + return option; + } + + /** + * Transform part to sql expression + */ + private static void handleQueryPart(StringBuilder sql, Part part) { + sql.append("("); + + sql.append(part.getProperty()); + + switch (part.getType()) { + case SIMPLE_PROPERTY: + sql.append("=?"); + break; + case NEGATING_SIMPLE_PROPERTY: + sql.append("<>?"); + break; + case GREATER_THAN: + sql.append(">?"); + break; + case GREATER_THAN_EQUAL: + sql.append(">=?"); + break; + case LESS_THAN: + sql.append("<?"); + break; + case LESS_THAN_EQUAL: + sql.append("<=?"); + break; + case IS_NOT_NULL: + sql.append(" IS NOT NULL"); + break; + case IS_NULL: + sql.append(" IS NULL"); + break; + case BETWEEN: + sql.append(" BETWEEN ? AND ?"); + break; + case FALSE: + sql.append(" = FALSE"); + break; + case TRUE: + sql.append(" = TRUE"); + break; + case CONTAINING: + sql.append(" LIKE '%' || ? || '%'"); + break; + case NOT_CONTAINING: + sql.append(" NOT LIKE '%' || ? || '%'"); + break; + case LIKE: + sql.append(" LIKE '%' || ? || '%'"); + break; + case NOT_LIKE: + sql.append(" NOT LIKE '%' || ? || '%'"); + break; + case STARTING_WITH: + sql.append(" LIKE ? || '%'"); + break; + case ENDING_WITH: + sql.append(" LIKE '%' || ?"); + break; + case IN: + sql.append(" IN ?"); + break; + case NOT_IN: + sql.append(" NOT IN ?"); + break; + case REGEX: + sql.append(" REGEXP ?"); + break; + case NEAR: + case AFTER: + case BEFORE: + case EXISTS: + default: + throw new UnsupportedOperationException(part.getType() + " is not supported!"); + } + + sql.append(")"); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteRepositoryQuery.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteRepositoryQuery.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteRepositoryQuery.java new file mode 100644 index 0000000..493c5f2 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/IgniteRepositoryQuery.java @@ -0,0 +1,311 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.springdata20.repository.query; + +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import javax.cache.Cache; +import org.apache.ignite.IgniteCache; +import org.apache.ignite.cache.query.Query; +import org.apache.ignite.cache.query.QueryCursor; +import org.apache.ignite.cache.query.SqlFieldsQuery; +import org.apache.ignite.cache.query.SqlQuery; +import org.apache.ignite.internal.processors.cache.CacheEntryImpl; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.domain.SliceImpl; +import org.springframework.data.domain.Sort; +import org.springframework.data.projection.ProjectionFactory; +import org.springframework.data.repository.core.RepositoryMetadata; +import org.springframework.data.repository.query.QueryMethod; +import org.springframework.data.repository.query.RepositoryQuery; + +/** + * Ignite SQL query implementation. + */ +@SuppressWarnings("unchecked") +public class IgniteRepositoryQuery implements RepositoryQuery { + /** Defines the way how to process query result */ + private enum ReturnStrategy { + /** Need to return only one value. */ + ONE_VALUE, + + /** Need to return one cache entry */ + CACHE_ENTRY, + + /** Need to return list of cache entries */ + LIST_OF_CACHE_ENTRIES, + + /** Need to return list of values */ + LIST_OF_VALUES, + + /** Need to return list of lists */ + LIST_OF_LISTS, + + /** Need to return slice */ + SLICE_OF_VALUES, + + /** Slice of cache entries. */ + SLICE_OF_CACHE_ENTRIES, + + /** Slice of lists. */ + SLICE_OF_LISTS + } + + /** Type. */ + private final Class<?> type; + + /** Sql. */ + private final IgniteQuery qry; + + /** Cache. */ + private final IgniteCache cache; + + /** Method. */ + private final Method mtd; + + /** Metadata. */ + private final RepositoryMetadata metadata; + + /** Factory. */ + private final ProjectionFactory factory; + + /** Return strategy. */ + private final ReturnStrategy returnStgy; + + /** + * @param metadata Metadata. + * @param qry Query. + * @param mtd Method. + * @param factory Factory. + * @param cache Cache. + */ + public IgniteRepositoryQuery(RepositoryMetadata metadata, IgniteQuery qry, + Method mtd, ProjectionFactory factory, IgniteCache cache) { + type = metadata.getDomainType(); + this.qry = qry; + this.cache = cache; + this.metadata = metadata; + this.mtd = mtd; + this.factory = factory; + + returnStgy = calcReturnType(mtd, qry.isFieldQuery()); + } + + /** {@inheritDoc} */ + @Override public Object execute(Object[] prmtrs) { + Query qry = prepareQuery(prmtrs); + + QueryCursor qryCursor = cache.query(qry); + + return transformQueryCursor(prmtrs, qryCursor); + } + + /** {@inheritDoc} */ + @Override public QueryMethod getQueryMethod() { + return new QueryMethod(mtd, metadata, factory); + } + + /** + * @param mtd Method. + * @param isFieldQry Is field query. + * @return Return strategy type. + */ + private ReturnStrategy calcReturnType(Method mtd, boolean isFieldQry) { + Class<?> returnType = mtd.getReturnType(); + + if (returnType.isAssignableFrom(ArrayList.class)) { + if (isFieldQry) { + if (hasAssignableGenericReturnTypeFrom(ArrayList.class, mtd)) + return ReturnStrategy.LIST_OF_LISTS; + } + else if (hasAssignableGenericReturnTypeFrom(Cache.Entry.class, mtd)) + return ReturnStrategy.LIST_OF_CACHE_ENTRIES; + + return ReturnStrategy.LIST_OF_VALUES; + } + else if (returnType == Slice.class) { + if (isFieldQry) { + if (hasAssignableGenericReturnTypeFrom(ArrayList.class, mtd)) + return ReturnStrategy.SLICE_OF_LISTS; + } + else if (hasAssignableGenericReturnTypeFrom(Cache.Entry.class, mtd)) + return ReturnStrategy.SLICE_OF_CACHE_ENTRIES; + + return ReturnStrategy.SLICE_OF_VALUES; + } + else if (Cache.Entry.class.isAssignableFrom(returnType)) + return ReturnStrategy.CACHE_ENTRY; + else + return ReturnStrategy.ONE_VALUE; + } + + /** + * @param cls Class 1. + * @param mtd Method. + * @return if {@code mtd} return type is assignable from {@code cls} + */ + private boolean hasAssignableGenericReturnTypeFrom(Class<?> cls, Method mtd) { + Type[] actualTypeArguments = ((ParameterizedType)mtd.getGenericReturnType()).getActualTypeArguments(); + + if (actualTypeArguments.length == 0) + return false; + + if (actualTypeArguments[0] instanceof ParameterizedType) { + ParameterizedType type = (ParameterizedType)actualTypeArguments[0]; + + Class<?> type1 = (Class)type.getRawType(); + + return type1.isAssignableFrom(cls); + } + + if (actualTypeArguments[0] instanceof Class) { + Class typeArg = (Class)actualTypeArguments[0]; + + return typeArg.isAssignableFrom(cls); + } + + return false; + } + + /** + * @param prmtrs Prmtrs. + * @param qryCursor Query cursor. + * @return Query cursor or slice + */ + @Nullable private Object transformQueryCursor(Object[] prmtrs, QueryCursor qryCursor) { + if (this.qry.isFieldQuery()) { + Iterable<ArrayList> qryIter = (Iterable<ArrayList>)qryCursor; + + switch (returnStgy) { + case LIST_OF_VALUES: + ArrayList list = new ArrayList(); + + for (ArrayList entry : qryIter) + list.add(entry.get(0)); + + return list; + case ONE_VALUE: + Iterator<ArrayList> iter = qryIter.iterator(); + + if (iter.hasNext()) + return iter.next().get(0); + + return null; + case SLICE_OF_VALUES: + ArrayList content = new ArrayList(); + + for (ArrayList entry : qryIter) + content.add(entry.get(0)); + + return new SliceImpl(content, (Pageable)prmtrs[prmtrs.length - 1], true); + case SLICE_OF_LISTS: + return new SliceImpl(qryCursor.getAll(), (Pageable)prmtrs[prmtrs.length - 1], true); + case LIST_OF_LISTS: + return qryCursor.getAll(); + default: + throw new IllegalStateException(); + } + } + else { + Iterable<CacheEntryImpl> qryIter = (Iterable<CacheEntryImpl>)qryCursor; + + switch (returnStgy) { + case LIST_OF_VALUES: + ArrayList list = new ArrayList(); + + for (CacheEntryImpl entry : qryIter) + list.add(entry.getValue()); + + return list; + case ONE_VALUE: + Iterator<CacheEntryImpl> iter1 = qryIter.iterator(); + + if (iter1.hasNext()) + return iter1.next().getValue(); + + return null; + case CACHE_ENTRY: + Iterator<CacheEntryImpl> iter2 = qryIter.iterator(); + + if (iter2.hasNext()) + return iter2.next(); + + return null; + case SLICE_OF_VALUES: + ArrayList content = new ArrayList(); + + for (CacheEntryImpl entry : qryIter) + content.add(entry.getValue()); + + return new SliceImpl(content, (Pageable)prmtrs[prmtrs.length - 1], true); + case SLICE_OF_CACHE_ENTRIES: + return new SliceImpl(qryCursor.getAll(), (Pageable)prmtrs[prmtrs.length - 1], true); + case LIST_OF_CACHE_ENTRIES: + return qryCursor.getAll(); + default: + throw new IllegalStateException(); + } + } + } + + /** + * @param prmtrs Prmtrs. + * @return prepared query for execution + */ + @NotNull private Query prepareQuery(Object[] prmtrs) { + Object[] parameters = prmtrs; + String sql = qry.sql(); + + Query query; + + switch (qry.options()) { + case SORTING: + sql = IgniteQueryGenerator.addSorting(new StringBuilder(sql), + (Sort)parameters[parameters.length - 1]).toString(); + parameters = Arrays.copyOfRange(parameters, 0, parameters.length - 1); + break; + case PAGINATION: + sql = IgniteQueryGenerator.addPaging(new StringBuilder(sql), + (Pageable)parameters[parameters.length - 1]).toString(); + parameters = Arrays.copyOfRange(parameters, 0, parameters.length - 1); + break; + } + + if (qry.isFieldQuery()) { + SqlFieldsQuery sqlFieldsQry = new SqlFieldsQuery(sql); + sqlFieldsQry.setArgs(parameters); + + query = sqlFieldsQry; + } + else { + SqlQuery sqlQry = new SqlQuery(type, sql); + sqlQry.setArgs(parameters); + + query = sqlQry; + } + + return query; + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/package-info.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/package-info.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/package-info.java new file mode 100644 index 0000000..c9f90dc --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/query/package-info.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * <!-- Package description. --> + * Package includes classes that integrates with Apache Ignite SQL engine. + */ +package org.apache.ignite.springdata20.repository.query; http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/ConditionFalse.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/ConditionFalse.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/ConditionFalse.java new file mode 100644 index 0000000..daeacf5 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/ConditionFalse.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.springdata20.repository.support; + +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; + +/** + * Always false condition. + * Tells spring context never load bean with such Condition. + */ +public class ConditionFalse implements Condition { + /**{@inheritDoc}*/ + @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + return false; + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/IgniteRepositoryFactory.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/IgniteRepositoryFactory.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/IgniteRepositoryFactory.java new file mode 100644 index 0000000..ea51b7d --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/IgniteRepositoryFactory.java @@ -0,0 +1,156 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ignite.springdata20.repository.support; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import org.apache.ignite.Ignite; +import org.apache.ignite.Ignition; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.springdata20.repository.IgniteRepository; +import org.apache.ignite.springdata20.repository.config.Query; +import org.apache.ignite.springdata20.repository.config.RepositoryConfig; +import org.apache.ignite.springdata20.repository.query.IgniteQuery; +import org.apache.ignite.springdata20.repository.query.IgniteQueryGenerator; +import org.apache.ignite.springdata20.repository.query.IgniteRepositoryQuery; +import org.springframework.data.repository.core.EntityInformation; +import org.springframework.data.repository.core.RepositoryInformation; +import org.springframework.data.repository.core.RepositoryMetadata; +import org.springframework.data.repository.core.support.AbstractEntityInformation; +import org.springframework.data.repository.core.support.RepositoryFactorySupport; +import org.springframework.data.repository.query.EvaluationContextProvider; +import org.springframework.data.repository.query.QueryLookupStrategy; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** + * Crucial for spring-data functionality class. Create proxies for repositories. + */ +public class IgniteRepositoryFactory extends RepositoryFactorySupport { + /** Ignite instance */ + private Ignite ignite; + + /** Mapping of a repository to a cache. */ + private final Map<Class<?>, String> repoToCache = new HashMap<>(); + + /** + * Creates the factory with initialized {@link Ignite} instance. + * + * @param ignite + */ + public IgniteRepositoryFactory(Ignite ignite) { + this.ignite = ignite; + } + + /** + * Initializes the factory with provided {@link IgniteConfiguration} that is used to start up an underlying + * {@link Ignite} instance. + * + * @param cfg Ignite configuration. + */ + public IgniteRepositoryFactory(IgniteConfiguration cfg) { + this.ignite = Ignition.start(cfg); + } + + /** + * Initializes the factory with provided a configuration under {@code springCfgPath} that is used to start up + * an underlying {@link Ignite} instance. + * + * @param springCfgPath A path to Ignite configuration. + */ + public IgniteRepositoryFactory(String springCfgPath) { + this.ignite = Ignition.start(springCfgPath); + } + + /** {@inheritDoc} */ + @Override public <T, ID> EntityInformation<T, ID> getEntityInformation(Class<T> domainClass) { + return new AbstractEntityInformation<T, ID>(domainClass) { + @Override public ID getId(T entity) { + return null; + } + + @Override public Class<ID> getIdType() { + return null; + } + }; + } + + /** {@inheritDoc} */ + @Override protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) { + return IgniteRepositoryImpl.class; + } + + /** {@inheritDoc} */ + @Override protected RepositoryMetadata getRepositoryMetadata(Class<?> repoItf) { + Assert.notNull(repoItf, "Repository interface must be set."); + Assert.isAssignable(IgniteRepository.class, repoItf, "Repository must implement IgniteRepository interface."); + + RepositoryConfig annotation = repoItf.getAnnotation(RepositoryConfig.class); + + Assert.notNull(annotation, "Set a name of an Apache Ignite cache using @RepositoryConfig annotation to map " + + "this repository to the underlying cache."); + + Assert.hasText(annotation.cacheName(), "Set a name of an Apache Ignite cache using @RepositoryConfig " + + "annotation to map this repository to the underlying cache."); + + repoToCache.put(repoItf, annotation.cacheName()); + + return super.getRepositoryMetadata(repoItf); + } + + /** {@inheritDoc} */ + @Override protected Object getTargetRepository(RepositoryInformation metadata) { + return getTargetRepositoryViaReflection(metadata, + ignite.getOrCreateCache(repoToCache.get(metadata.getRepositoryInterface()))); + } + + /** {@inheritDoc} */ + @Override protected Optional<QueryLookupStrategy> getQueryLookupStrategy(final QueryLookupStrategy.Key key, + EvaluationContextProvider evaluationCtxProvider) { + return Optional.of((mtd, metadata, factory, namedQueries) -> { + + final Query annotation = mtd.getAnnotation(Query.class); + + if (annotation != null) { + String qryStr = annotation.value(); + + if (key != QueryLookupStrategy.Key.CREATE && StringUtils.hasText(qryStr)) { + return new IgniteRepositoryQuery(metadata, + new IgniteQuery(qryStr, isFieldQuery(qryStr), IgniteQueryGenerator.getOptions(mtd)), + mtd, factory, ignite.getOrCreateCache(repoToCache.get(metadata.getRepositoryInterface()))); + } + } + + if (key == QueryLookupStrategy.Key.USE_DECLARED_QUERY) { + throw new IllegalStateException("To use QueryLookupStrategy.Key.USE_DECLARED_QUERY, pass " + + "a query string via org.apache.ignite.springdata.repository.config.Query annotation."); + } + + return new IgniteRepositoryQuery(metadata, IgniteQueryGenerator.generateSql(mtd, metadata), mtd, + factory, ignite.getOrCreateCache(repoToCache.get(metadata.getRepositoryInterface()))); + }); + } + + /** + * @param qry Query string. + * @return {@code true} if query is SQLFieldsQuery. + */ + private boolean isFieldQuery(String qry) { + return qry.matches("^SELECT.*") && !qry.matches("^SELECT\\s+(?:\\w+\\.)?+\\*.*"); + } +} http://git-wip-us.apache.org/repos/asf/ignite/blob/22040a3c/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/IgniteRepositoryFactoryBean.java ---------------------------------------------------------------------- diff --git a/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/IgniteRepositoryFactoryBean.java b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/IgniteRepositoryFactoryBean.java new file mode 100644 index 0000000..36c3b65 --- /dev/null +++ b/modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/IgniteRepositoryFactoryBean.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.springdata20.repository.support; + +import java.io.Serializable; +import org.apache.ignite.Ignite; +import org.apache.ignite.IgniteException; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.springdata20.repository.IgniteRepository; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.data.repository.Repository; +import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport; +import org.springframework.data.repository.core.support.RepositoryFactorySupport; + +/** + * Apache Ignite repository factory bean. + * + * The repository requires to define one of the parameters below in your Spring application configuration in order + * to get an access to Apache Ignite cluster: + * <ul> + * <li>{@link Ignite} instance bean named "igniteInstance"</li> + * <li>{@link IgniteConfiguration} bean named "igniteCfg"</li> + * <li>A path to Ignite's Spring XML configuration named "igniteSpringCfgPath"</li> + * <ul/> + * + * @param <T> Repository type, {@link IgniteRepository} + * @param <S> Domain object class. + * @param <ID> Domain object key, super expects {@link Serializable}. + */ +public class IgniteRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> + extends RepositoryFactoryBeanSupport<T, S, ID> implements ApplicationContextAware { + /** Application context. */ + private ApplicationContext ctx; + + /** + * @param repositoryInterface Repository interface. + */ + protected IgniteRepositoryFactoryBean(Class<? extends T> repositoryInterface) { + super(repositoryInterface); + } + + /** {@inheritDoc} */ + @Override public void setApplicationContext(ApplicationContext context) throws BeansException { + this.ctx = context; + } + + /** {@inheritDoc} */ + @Override protected RepositoryFactorySupport createRepositoryFactory() { + try { + Ignite ignite = (Ignite)ctx.getBean("igniteInstance"); + + return new IgniteRepositoryFactory(ignite); + } + catch (BeansException ex) { + try { + IgniteConfiguration cfg = (IgniteConfiguration)ctx.getBean("igniteCfg"); + + return new IgniteRepositoryFactory(cfg); + } + catch (BeansException ex2) { + try { + String path = (String)ctx.getBean("igniteSpringCfgPath"); + + return new IgniteRepositoryFactory(path); + } + catch (BeansException ex3) { + throw new IgniteException("Failed to initialize Ignite repository factory. Ignite instance or" + + " IgniteConfiguration or a path to Ignite's spring XML configuration must be defined in the" + + " application configuration"); + } + } + } + } +}
