diff --git a/.gitignore b/.gitignore index 700dec6..40c3cec 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,73 @@ target *.ipr *.iws atlassian-ide-plugin.xml +### Maven template +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties + +# Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) +!/.mvn/wrapper/maven-wrapper.jar +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties +### Gradle template +.gradle +/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100755 index 0000000..cd6091c --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,42 @@ +#!groovy +node("master") { + properties([[$class : 'BuildDiscarderProperty', + strategy: [$class : 'LogRotator', artifactDaysToKeepStr: '', + artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '10']]]) + + def mvnHome = tool 'mvn' + def mvnJdk8Image = "orientdb/mvn-gradle-zulu-jdk-8" + + def containerName = env.JOB_NAME.replaceAll(/\//, "_") + + "_build_${currentBuild.number}" + + def appNameLabel = "docker_ci"; + def taskLabel = env.JOB_NAME.replaceAll(/\//, "_") + + + stage('Source checkout') { + + checkout scm + } + + stage('Run tests on Java8') { + lock("label": "memory", "quantity": 4) { + docker.image("${mvnJdk8Image}").inside("--label collectd_docker_app=${appNameLabel} --label collectd_docker_task=${taskLabel} " + + "--name ${containerName} --memory=4g ${env.VOLUMES}") { + try { + + sh "${mvnHome}/bin/mvn --batch-mode -V -U -fae clean deploy -Dmaven.test.failure.ignore=true -Dsurefire.useFile=false" + } catch (e) { + currentBuild.result = 'FAILURE' + + slackSend(color: 'bad', message: "FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})\n${e}") + } finally { + junit allowEmptyResults: true, testResults: '**/target/surefire-reports/TEST-*.xml' + + } + } + } + } + +} + diff --git a/README.md b/README.md index 6dbfcd2..9125c91 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@ -Spring Data OrientDB -==================== +# Spring Data OrientDB The primary goal of the [Spring Data](http://projects.spring.io/) project is to make it easier to build Spring-powered applications that use new data access technologies such as non-relational databases, map-reduce frameworks, and cloud based data services. @@ -8,3 +7,60 @@ The SpringData OrientDB project will implement easy to use APIs for using Orient The document module is based on the [Spring Data MongoDB](http://projects.spring.io/spring-data-mongodb/) project. [![Build Status](https://drone.io/github.com/vidakovic/spring-data-orientdb/status.png)](https://drone.io/github.com/vidakovic/spring-data-orientdb/latest) + +To include OrientDB Spring Data in your Java project via Maven, put one of the snippets below in your pom.xml or build.gradle + +## Object API + +### Dependency management + +Maven +```xml + + com.orientechnologies + spring-data-orientdb-object + 0.13 + +``` + +Gradle: +```groovy + group: 'com.orientechnologies', name: 'spring-data-orientdb-object', version: '0.13' +``` + +### Example + +To + + +## Graph API + +Maven: +```xml + + com.orientechnologies + spring-data-orientdb-graph + 0.13 + +``` + +Gradle: +```groovy + group: 'com.orientechnologies', name: 'spring-data-orientdb-graph', version: '0.13' +``` + + +### Document API +```xml + + com.orientechnologies + spring-data-orientdb-document + 0.13 + +``` + +Gradle: +```groovy + group: 'com.orientechnologies', name: 'spring-data-orientdb-document', version: '0.13' +``` + diff --git a/_base/script/upd_version.sh b/_base/script/upd_version.sh new file mode 100755 index 0000000..6a37e66 --- /dev/null +++ b/_base/script/upd_version.sh @@ -0,0 +1,20 @@ +#!/bin/bash +if [ -z "$1" -o -z "$2" -o -z "$3" ] +then + echo "SYNTAX ERROR, USE: upd-version.sh " + exit +fi + +echo "Updating version from $2 to $3 in directory $1 and subfolders" + +TFILE="/tmp/out.tmp.$$" +for filename in $(grep -r "$2" --include "pom.xml" $1|cut -f 1 -d :) +do + if [ -f $filename -a -r $filename ]; then + #/bin/cp -f $filename ${filename}.old + sed "s/$2/$3/g" "$filename" > $TFILE && mv $TFILE "$filename" + else + echo "Error: Cannot read $filename" + fi +done +/bin/rm $TFILE 2>/dev/null diff --git a/pom.xml b/pom.xml index bd6f936..a1b3464 100644 --- a/pom.xml +++ b/pom.xml @@ -14,18 +14,22 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT pom Spring Data OrientDB Spring Data OrientDB - http://www.orientechnologies.com + http://orientdb.com + 2015 + + OrientDB + http://orientdb.com + Apache 2 @@ -33,6 +37,13 @@ + + + google groups + http://groups.google.com/group/orient-database/topics + + + spring-data-orientdb-commons spring-data-orientdb-document @@ -44,44 +55,88 @@ spring-data-orientdb-samples/spring-boot-orientdb-shiro + + scm:git:git@github.com:orientechnologies/spring-data-orientdb.git + scm:git:git@github.com:orientechnologies/spring-data-orientdb.git + scm:git:git@github.com:orientechnologies/spring-data-orientdb.git + HEAD + + + GitHub Issues + https://github.com/orientechnologies/spring-data-orientdb/issues + + + + jenkins + http://helios.orientdb.com/ + + + + + sonatype-nexus-staging + OrientDB Maven2 Repository + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + sonatype-nexus-snapshots + OrientDB Maven2 Snapshot Repository + https://oss.sonatype.org/content/repositories/snapshots + false + + + + + + sonatype-nexus-snapshots + Sonatype Nexus Snapshots + https://oss.sonatype.org/content/repositories/snapshots + + false + + + true + + + UTF-8 UTF-8 UTF-8 - 1.7 - 1.7 + 1.8 + 1.8 yyyy-MM-dd HH:mm:ssZ - + ${project.groupId}.orientdb*;version=${project.version};-noimport:=true * - - + + https://oss.sonatype.org/content/repositories/snapshots/ - 1.7.13 - 1.1.3 - 2.1.8 - 1.8.7 - 4.2.4.RELEASE - 1.11.2.RELEASE - 1.3.1.RELEASE - 3.7.2 + 1.7.22 + 1.1.9 + 2.2.37 + 1.8.9 + 4.3.8.RELEASE + 1.13.11.RELEASE + 1.5.3.RELEASE + 3.9.2 1.4.1 4.12 - 6.8.21 - 2.4.0 + 2.9.0 + https://oss.sonatype.org/content/repositories/snapshots/ + l.garulli Luca Garulli - l.garulli@orientechnologies.com - Orientechnologies - http://www.orientechnologies.com + l.garulli@orientdb.com + OrientDB + http://orientdb.com architect developer @@ -89,10 +144,18 @@ +1 + + r.franchini + Roberto Franchini + r.franchini@orientdb.com + OrientDB + http://orientdb.com + +1 + trainings Dzmitry Naskou - + Developer @@ -110,7 +173,7 @@ sleroy Sylvain Leroy - + Developer @@ -119,7 +182,7 @@ vidakovic Aleksandar Vidakovic - + Developer @@ -127,32 +190,6 @@ - - scm:git:git@github.com:orientechnologies/spring-data-orientdb.git - scm:git:git@github.com:orientechnologies/spring-data-orientdb.git - scm:git:git@github.com:orientechnologies/spring-data-orientdb.git - - - GitHub Issues - https://github.com/orientechnologies/spring-data-orientdb/issues - - - jenkins - http://datastorm.com.ua/ - - - - sonatype-nexus-staging - OrientDB Maven2 Repository - https://oss.sonatype.org/service/local/staging/deploy/maven2 - - - sonatype-nexus-snapshots - OrientDB Maven2 Snapshot Repository - https://oss.sonatype.org/content/repositories/snapshots - - - @@ -324,10 +361,11 @@ ${junit.version} - org.testng - testng - ${testng.version} + org.assertj + assertj-core + 2.5.0 + org.springframework spring-test @@ -352,12 +390,6 @@ - - - spring-libs-snapshot - http://repo.spring.io/libs-snapshot - - spring-plugins-release @@ -388,9 +420,21 @@ + + + + + + + + + junit + junit + test + - org.testng - testng + org.assertj + assertj-core test @@ -464,10 +508,6 @@ org.apache.maven.plugins maven-surefire-plugin 2.18 - - methods - 5 - org.apache.maven.plugins @@ -535,7 +575,7 @@ - + @@ -556,30 +596,23 @@ ${shaded.name} false - - + + META-INF/spring.handlers - + META-INF/spring.schemas - + META-INF/spring.factories - + META-INF/cxf/org.apache.cxf.bus.factory - + META-INF/cxf/bus-extensions.txt - + ${shaded.main} ${maven.compiler.source} @@ -699,4 +732,34 @@ + + + + release-sign-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + + + + diff --git a/spring-boot-orientdb-autoconfigure/pom.xml b/spring-boot-orientdb-autoconfigure/pom.xml index 08fface..b5b3b82 100644 --- a/spring-boot-orientdb-autoconfigure/pom.xml +++ b/spring-boot-orientdb-autoconfigure/pom.xml @@ -1,17 +1,15 @@ - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT ../pom.xml - org.springframework.boot + com.orientechnologies spring-boot-orientdb-autoconfigure jar Spring Boot OrientDB @@ -30,17 +28,17 @@ - org.springframework.data + com.orientechnologies spring-data-orientdb-document ${project.version} - org.springframework.data + com.orientechnologies spring-data-orientdb-object ${project.version} - org.springframework.data + com.orientechnologies spring-data-orientdb-graph ${project.version} diff --git a/spring-boot-orientdb-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orient/OrientAutoConfiguration.java b/spring-boot-orientdb-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orient/OrientAutoConfiguration.java index f0ddf2a..ce71508 100644 --- a/spring-boot-orientdb-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orient/OrientAutoConfiguration.java +++ b/spring-boot-orientdb-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orient/OrientAutoConfiguration.java @@ -4,18 +4,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.orient.commons.core.OrientDatabaseFactory; -import org.springframework.data.orient.commons.core.OrientOperations; import org.springframework.data.orient.commons.core.OrientTransactionManager; +import org.springframework.data.orient.commons.web.config.OrientWebConfigurer; import org.springframework.data.orient.object.OrientObjectDatabaseFactory; import org.springframework.data.orient.object.OrientObjectOperations; import org.springframework.data.orient.object.OrientObjectTemplate; -import org.springframework.data.orient.commons.web.config.OrientWebConfigurer; import org.springframework.transaction.PlatformTransactionManager; @Configuration @@ -25,21 +23,21 @@ public class OrientAutoConfiguration { @Autowired private OrientProperties properties; - + @Bean - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) @ConditionalOnMissingBean(PlatformTransactionManager.class) public PlatformTransactionManager transactionManager(OrientDatabaseFactory factory) { return new OrientTransactionManager(factory); } - + @Bean @ConditionalOnMissingBean(OrientObjectDatabaseFactory.class) public OrientObjectDatabaseFactory objectDatabaseFactory() { OrientObjectDatabaseFactory factory = new OrientObjectDatabaseFactory(); - + configure(factory); - + return factory; } @@ -63,7 +61,6 @@ protected void configure(OrientDatabaseFactory factory) { factory.setUrl(properties.getUrl()); factory.setUsername(properties.getUsername()); factory.setPassword(properties.getPassword()); - factory.setMaxPoolSize(properties.getMinPoolSize()); factory.setMaxPoolSize(properties.getMaxPoolSize()); } diff --git a/spring-boot-orientdb-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orient/OrientProperties.java b/spring-boot-orientdb-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orient/OrientProperties.java index 0ab750a..db940cf 100644 --- a/spring-boot-orientdb-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orient/OrientProperties.java +++ b/spring-boot-orientdb-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orient/OrientProperties.java @@ -7,13 +7,11 @@ public class OrientProperties { private String url; - + private String username; - + private String password; - - private int minPoolSize = OrientDatabaseFactory.DEFAULT_MIN_POOL_SIZE; - + private int maxPoolSize = OrientDatabaseFactory.DEFAULT_MAX_POOL_SIZE; public String getUrl() { @@ -40,14 +38,6 @@ public void setPassword(String password) { this.password = password; } - public int getMinPoolSize() { - return minPoolSize; - } - - public void setMinPoolSize(int minPoolSize) { - this.minPoolSize = minPoolSize; - } - public int getMaxPoolSize() { return maxPoolSize; } diff --git a/spring-data-orientdb-benchmarks/pom.xml b/spring-data-orientdb-benchmarks/pom.xml index ce73a55..adc1750 100644 --- a/spring-data-orientdb-benchmarks/pom.xml +++ b/spring-data-orientdb-benchmarks/pom.xml @@ -1,13 +1,11 @@ - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT ../pom.xml diff --git a/spring-data-orientdb-commons/pom.xml b/spring-data-orientdb-commons/pom.xml index 1cba99b..7aaa2d5 100644 --- a/spring-data-orientdb-commons/pom.xml +++ b/spring-data-orientdb-commons/pom.xml @@ -1,13 +1,11 @@ - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT ../pom.xml diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/AbstractOrientDatabaseFactory.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/AbstractOrientDatabaseFactory.java index b0f611d..d385989 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/AbstractOrientDatabaseFactory.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/AbstractOrientDatabaseFactory.java @@ -13,37 +13,43 @@ /** * A base factory for creating {@link com.orientechnologies.orient.core.db.ODatabase} objects. * - * @author Dzmitry_Naskou * @param the type of database to handle + * @author Dzmitry_Naskou */ public abstract class AbstractOrientDatabaseFactory implements OrientDatabaseFactory { - /** The logger. */ + /** + * The logger. + */ private static Logger log = LoggerFactory.getLogger(AbstractOrientDatabaseFactory.class); - /** The username. */ + /** + * The username. + */ protected String username = DEFAULT_USERNAME; - /** The password. */ + /** + * The password. + */ protected String password = DEFAULT_PASSWORD; - /** The min pool size. */ - protected int minPoolSize = DEFAULT_MIN_POOL_SIZE; - /** The max pool size. */ + /** + * The max pool size. + */ protected int maxPoolSize = DEFAULT_MAX_POOL_SIZE; protected Boolean autoCreate; protected String url; - + @PostConstruct public void init() { notNull(url); notNull(username); notNull(password); - if(autoCreate==null) { + if (autoCreate == null) { autoCreate = !getUrl().startsWith("remote:"); } @@ -64,24 +70,19 @@ public void init() { protected abstract ODatabaseInternal newDatabase(); public ODatabase db() { - ODatabase db; - if(!ODatabaseRecordThreadLocal.INSTANCE.isDefined()) { - db = openDatabase(); - log.debug("acquire db from pool {}", db.hashCode()); - } else { - db = (ODatabase)ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner(); - - if(db.isClosed()) { - db = openDatabase(); - log.debug("re-opened db {}", db.hashCode()); - } else { + ODatabase db = openDatabase(); log.debug("use existing db {}", db.hashCode()); - } - } - return db; } + + @Override + public void dropDatabase() { + ODatabaseInternal database = newDatabase(); + database.open(username, password); + database.drop(); + } + protected void createDatabase(ODatabase db) { if (autoCreate) { if (!db.exists()) { @@ -145,23 +146,6 @@ public void setPassword(String password) { this.password = password; } - /** - * Gets the min pool size. - * - * @return the min pool size - */ - public int getMinPoolSize() { - return minPoolSize; - } - - /** - * Sets the min pool size. - * - * @param minPoolSize the new min pool size - */ - public void setMinPoolSize(int minPoolSize) { - this.minPoolSize = minPoolSize; - } /** * Gets the max pool size. diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/AbstractOrientOperations.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/AbstractOrientOperations.java index d7da32b..2fabce7 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/AbstractOrientOperations.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/AbstractOrientOperations.java @@ -1,12 +1,10 @@ package org.springframework.data.orient.commons.core; -import com.orientechnologies.common.exception.OException; import com.orientechnologies.orient.core.cache.OLocalRecordCache; import com.orientechnologies.orient.core.command.OCommandOutputListener; import com.orientechnologies.orient.core.command.OCommandRequest; import com.orientechnologies.orient.core.db.ODatabase; import com.orientechnologies.orient.core.db.ODatabaseListener; -import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.dictionary.ODictionary; import com.orientechnologies.orient.core.exception.OTransactionException; import com.orientechnologies.orient.core.hook.ORecordHook; @@ -16,7 +14,6 @@ import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.security.OSecurityUser; -import com.orientechnologies.orient.core.metadata.security.OUser; import com.orientechnologies.orient.core.query.OQuery; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.OCommandSQL; @@ -26,7 +23,6 @@ import com.orientechnologies.orient.core.storage.ORecordMetadata; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.tx.OTransaction; -import com.orientechnologies.orient.core.version.ORecordVersion; import org.springframework.data.orient.commons.repository.DetachMode; import java.io.IOException; @@ -36,7 +32,6 @@ import java.util.concurrent.Callable; public abstract class AbstractOrientOperations implements OrientOperations { - //private static final Logger logger = LoggerFactory.getLogger(AbstractOrientOperations.class); protected final OrientDatabaseFactory dbf; @@ -117,17 +112,14 @@ public > DB unregisterHook(ORecordHook hook) { } @Override - public ORecordHook.RESULT callbackHooks(ORecordHook.TYPE type, OIdentifiable id) { - return dbf.db().callbackHooks(type, id); - } - - @Override - public void backup(OutputStream out, Map options, Callable callable, OCommandOutputListener listener, int compressionLevel, int bufferSize) throws IOException { + public void backup(OutputStream out, Map options, Callable callable, OCommandOutputListener listener, + int compressionLevel, int bufferSize) throws IOException { dbf.db().backup(out, options, callable, listener, compressionLevel, bufferSize); } @Override - public void restore(InputStream in, Map options, Callable callable, OCommandOutputListener listener) throws IOException { + public void restore(InputStream in, Map options, Callable callable, OCommandOutputListener listener) + throws IOException { dbf.db().restore(in, options, callable, listener); } @@ -166,7 +158,6 @@ public ORecordMetadata getRecordMetadata(ORID rid) { return dbf.db().getRecordMetadata(rid); } - @Override public ODictionary getDictionary() { return dbf.db().getDictionary(); @@ -322,7 +313,8 @@ public T load(T entity, String fetchPlan, boolean ignoreCache, boolean loadTombs } @Override - public T load(ORID recordId, String fetchPlan, boolean ignoreCache, boolean loadTombstone, OStorage.LOCKING_STRATEGY lockingStrategy) { + public T load(ORID recordId, String fetchPlan, boolean ignoreCache, boolean loadTombstone, + OStorage.LOCKING_STRATEGY lockingStrategy) { return dbf.db().load(recordId, fetchPlan, ignoreCache, loadTombstone, lockingStrategy); } @@ -337,7 +329,8 @@ public S save(S entity, String cluster) { } @Override - public S save(S entity, ODatabase.OPERATION_MODE mode, boolean forceCreate, ORecordCallback recordCallback, ORecordCallback recordUpdatedCallback) { + public S save(S entity, ODatabase.OPERATION_MODE mode, boolean forceCreate, + ORecordCallback recordCallback, ORecordCallback recordUpdatedCallback) { return dbf.db().save(entity, mode, forceCreate, recordCallback, recordUpdatedCallback); } @@ -399,13 +392,13 @@ public Collection getClusterNames() { @Override public int getClusterIdByName(String clusterName, Class clazz) { OClass oClass = dbf.db().getMetadata().getSchema().getClass(clazz); - for(int clusterId : oClass.getClusterIds()){ - if(getClusterNameById(clusterId).equals(clusterName)){ + for (int clusterId : oClass.getClusterIds()) { + if (getClusterNameById(clusterId).equals(clusterName)) { return clusterId; } } - throw new OException("Cluster " + clusterName + " not found"); + throw new IllegalArgumentException("Cluster " + clusterName + " not found"); } @Override @@ -449,7 +442,8 @@ public int addCluster(String type, String clusterName, String location, String d } @Override - public int addCluster(String type, String clusterName, int requestedId, String location, String dataSegmentName, Object... params) { + public int addCluster(String type, String clusterName, int requestedId, String location, String dataSegmentName, + Object... params) { return dbf.db().addCluster(type, clusterName, requestedId, location, dataSegmentName, params); } @@ -463,21 +457,6 @@ public int addCluster(String clusterName) { return dbf.db().addCluster(clusterName); } - @Override - public void freezeCluster(int iClusterId, boolean throwException) { - dbf.db().freezeCluster(iClusterId, throwException); - } - - @Override - public void freezeCluster(int iClusterId) { - dbf.db().freezeCluster(iClusterId); - } - - @Override - public void releaseCluster(int iClusterId) { - dbf.db().releaseCluster(iClusterId); - } - @Override public ODatabase delete(ORID recordId) { return dbf.db().delete(recordId); @@ -489,7 +468,7 @@ public ODatabase delete(T entity) { } @Override - public ODatabase delete(ORID rid, ORecordVersion version) { + public ODatabase delete(ORID rid, int version) { return dbf.db().delete(rid, version); } @@ -523,11 +502,6 @@ public OSecurityUser getUser() { return dbf.db().getUser(); } - @Override - public void setUser(OUser user) { - dbf.db().setUser(user); - } - @Override @SuppressWarnings("unchecked") public > RET detach(RET entities) { @@ -537,7 +511,7 @@ public > RET detach(RET entities) { result.add(detach(entity)); } - return (RET)result; + return (RET) result; } @Override @@ -549,7 +523,7 @@ public > RET detachAll(RET entities) { result.add(detachAll(entity)); } - return (RET)result; + return (RET) result; } @Override @@ -568,10 +542,10 @@ public > RET query(OQuery query, DetachMode detachMode, O return detachAll(result); case NONE: } - return result; } + @Override @SuppressWarnings("unchecked") public RET queryForObject(OSQLQuery query, DetachMode detachMode, Object... args) { @@ -591,7 +565,12 @@ public RET queryForObject(OSQLQuery query, DetachMode detachMode, Objec @Override @SuppressWarnings("unchecked") public RET queryForObject(OSQLQuery query, Object... args) { - return (RET)query(query, args).get(0); + List objects = query(query, args); + + if (objects.size() > 0) + return (RET) objects.get(0); + + return null; } @Override @@ -601,6 +580,7 @@ public RET command(OCommandRequest command) { @Override public RET command(OCommandSQL command, Object... args) { + return dbf.db().command(command).execute(args); } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientDatabaseFactory.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientDatabaseFactory.java index 7eebf11..65c63c1 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientDatabaseFactory.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientDatabaseFactory.java @@ -3,19 +3,23 @@ import com.orientechnologies.orient.core.db.ODatabase; public interface OrientDatabaseFactory { - /** Default database username. */ - public static final String DEFAULT_USERNAME = "admin"; + /** + * Default database username. + */ + String DEFAULT_USERNAME = "admin"; - /** Default database password. */ - public static final String DEFAULT_PASSWORD = "admin"; + /** + * Default database password. + */ + String DEFAULT_PASSWORD = "admin"; - /** Default minimum pool size. */ - public static final int DEFAULT_MIN_POOL_SIZE = 1; - /** Default maximum pool size. */ - public static final int DEFAULT_MAX_POOL_SIZE = 20; + /** + * Default maximum pool size. + */ + int DEFAULT_MAX_POOL_SIZE = 20; - public ODatabase db(); + ODatabase db(); ODatabase openDatabase(); @@ -31,11 +35,9 @@ public interface OrientDatabaseFactory { void setPassword(String password); - int getMinPoolSize(); - - void setMinPoolSize(int minPoolSize); - int getMaxPoolSize(); - + void setMaxPoolSize(int maxPoolSize); + + void dropDatabase(); } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientOperations.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientOperations.java index 75d1c98..bc55c2e 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientOperations.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientOperations.java @@ -5,7 +5,6 @@ import com.orientechnologies.orient.core.command.OCommandRequest; import com.orientechnologies.orient.core.db.ODatabase; import com.orientechnologies.orient.core.db.ODatabaseListener; -import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.dictionary.ODictionary; import com.orientechnologies.orient.core.exception.OTransactionException; import com.orientechnologies.orient.core.hook.ORecordHook; @@ -13,7 +12,6 @@ import com.orientechnologies.orient.core.intent.OIntent; import com.orientechnologies.orient.core.metadata.OMetadata; import com.orientechnologies.orient.core.metadata.security.OSecurityUser; -import com.orientechnologies.orient.core.metadata.security.OUser; import com.orientechnologies.orient.core.query.OQuery; import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLQuery; @@ -21,13 +19,15 @@ import com.orientechnologies.orient.core.storage.ORecordMetadata; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.tx.OTransaction; -import com.orientechnologies.orient.core.version.ORecordVersion; import org.springframework.data.orient.commons.repository.DetachMode; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.*; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.concurrent.Callable; public interface OrientOperations { @@ -48,9 +48,9 @@ public interface OrientOperations { > DB set(ODatabase.ATTRIBUTES attribute, Object value); - public void registerListener(ODatabaseListener listener); + void registerListener(ODatabaseListener listener); - public void unregisterListener(ODatabaseListener listener); + void unregisterListener(ODatabaseListener listener); Map getHooks(); @@ -60,11 +60,11 @@ public interface OrientOperations { > DB unregisterHook(ORecordHook hook); - ORecordHook.RESULT callbackHooks(ORecordHook.TYPE type, OIdentifiable id); + void backup(OutputStream out, Map options, Callable callable, OCommandOutputListener listener, + int compressionLevel, int bufferSize) throws IOException; - void backup(OutputStream out, Map options, Callable callable, OCommandOutputListener listener, int compressionLevel, int bufferSize) throws IOException; - - void restore(InputStream in, Map options, Callable callable, OCommandOutputListener listener) throws IOException; + void restore(InputStream in, Map options, Callable callable, OCommandOutputListener listener) + throws IOException; String getType(); @@ -84,10 +84,9 @@ public interface OrientOperations { boolean declareIntent(OIntent intent); + boolean isMVCC(); - public boolean isMVCC(); - - public > DB setMVCC(boolean mvcc); + > DB setMVCC(boolean mvcc); boolean isClosed(); @@ -118,9 +117,9 @@ public interface OrientOperations { OLocalRecordCache getLevel2Cache(); T newInstance(); - + T load(ORID recordId); - + T load(String recordId); T load(T entity); @@ -138,15 +137,37 @@ public interface OrientOperations { T load(ORID recordId, String fetchPlan, boolean ignoreCache, boolean loadTombstone, OStorage.LOCKING_STRATEGY lockingStrategy); S save(S entity); - + S save(S entity, String cluster); - S save(S entity, ODatabase.OPERATION_MODE mode, boolean forceCreate, ORecordCallback recordCallback, ORecordCallback recordUpdatedCallback); + S save(S entity, ODatabase.OPERATION_MODE mode, boolean forceCreate, + ORecordCallback recordCallback, ORecordCallback recordUpdatedCallback); + /** + * Counts the elements of a class + * + * @param className + * @return the count value + */ long countClass(String className); + /** + * Counts the elements of a class + * + * @param clazz + * @return the count value + */ long countClass(Class clazz); + /** + * Returns the count value for the {@link OSQLQuery} passed as parameter. + * Useful to count results of a query with conditions, e.g.: + * SELECT count(*) FROM Person WHERE age > 18 + * + * @param query that contains a count() + * @param args optional args for the query if it is parametrized + * @return the count value of the query + */ long count(OSQLQuery query, Object... args); long countClusterElements(String clusterName); @@ -169,7 +190,7 @@ public interface OrientOperations { ODatabase delete(T entity); - ODatabase delete(ORID rid, ORecordVersion version); + ODatabase delete(ORID rid, int version); int getDefaultClusterId(); @@ -197,12 +218,6 @@ public interface OrientOperations { int addCluster(String clusterName); - public void freezeCluster(int iClusterId, boolean throwException); - - public void freezeCluster(int iClusterId); - - public void releaseCluster(int iClusterId); - boolean isDefault(String clusterName); /** @@ -222,8 +237,7 @@ public interface OrientOperations { boolean existsClass(String className); /** - * Find field annotated with {@link com.orientechnologies.orient.core.annotation.OId} - * in entity and return it's value. + * Find field annotated with {@link com.orientechnologies.orient.core.annotation.OId} in entity and return it's value. * * @param entity Orient Entity * @return orient row ID or null if it is to found @@ -232,8 +246,6 @@ public interface OrientOperations { OSecurityUser getUser(); - void setUser(OUser user); - > RET detach(RET entities); > RET detachAll(RET list); @@ -253,6 +265,6 @@ public interface OrientOperations { RET command(OCommandRequest command); RET command(OCommandSQL command, Object... args); - + RET command(String sql, Object... args); } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientTransaction.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientTransaction.java index 89f6253..55f0eeb 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientTransaction.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientTransaction.java @@ -1,20 +1,23 @@ package org.springframework.data.orient.commons.core; import com.orientechnologies.orient.core.db.ODatabase; -import com.orientechnologies.orient.core.db.ODatabaseInternal; import com.orientechnologies.orient.core.tx.OTransaction; /** * The specific Orient Transaction. - * + * * @author Dzmitry_Naskou */ public class OrientTransaction { - /** The orient tx object. */ + /** + * The orient tx object. + */ private OTransaction tx; - /** The database. */ + /** + * The database. + */ private ODatabase database; public OTransaction getTx() { diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientTransactionManager.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientTransactionManager.java index d1cae4b..2ea03a0 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientTransactionManager.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/core/OrientTransactionManager.java @@ -16,17 +16,21 @@ /** * {@link org.springframework.transaction.PlatformTransactionManager} implementation * for OrientDB. - * + * * @author Dzmitry_Naskou */ public class OrientTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager { private static final long serialVersionUID = 1L; - /** The logger. */ + /** + * The logger. + */ private static Logger log = LoggerFactory.getLogger(OrientTransactionManager.class); - /** The database factory. */ + /** + * The database factory. + */ private OrientDatabaseFactory dbf; /** @@ -47,7 +51,7 @@ protected Object doGetTransaction() throws TransactionException { OrientTransaction tx = new OrientTransaction(); ODatabase db = (ODatabase) TransactionSynchronizationManager.getResource(getResourceFactory()); - + if (db != null) { tx.setDatabase(db); tx.setTx(db.getTransaction()); @@ -55,14 +59,14 @@ protected Object doGetTransaction() throws TransactionException { return tx; } - + /* (non-Javadoc) * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#isExistingTransaction(java.lang.Object) */ @Override protected boolean isExistingTransaction(Object transaction) throws TransactionException { OrientTransaction tx = (OrientTransaction) transaction; - + return tx.getTx() != null && tx.getTx().isActive(); } @@ -79,9 +83,9 @@ protected void doBegin(Object transaction, TransactionDefinition definition) thr tx.setDatabase(db); TransactionSynchronizationManager.bindResource(dbf, db); } - + log.debug("beginning transaction, db.hashCode() = {}", db.hashCode()); - + db.begin(); } @@ -92,9 +96,9 @@ protected void doBegin(Object transaction, TransactionDefinition definition) thr protected void doCommit(DefaultTransactionStatus status) throws TransactionException { OrientTransaction tx = (OrientTransaction) status.getTransaction(); ODatabase db = tx.getDatabase(); - + log.debug("committing transaction, db.hashCode() = {}", db.hashCode()); - + db.commit(); } @@ -105,12 +109,12 @@ protected void doCommit(DefaultTransactionStatus status) throws TransactionExcep protected void doRollback(DefaultTransactionStatus status) throws TransactionException { OrientTransaction tx = (OrientTransaction) status.getTransaction(); ODatabase db = tx.getDatabase(); - + log.debug("rolling back transaction, db.hashCode() = {}", db.hashCode()); - + db.rollback(); } - + /* (non-Javadoc) * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#doSetRollbackOnly(org.springframework.transaction.support.DefaultTransactionStatus) */ @@ -125,15 +129,15 @@ protected void doSetRollbackOnly(DefaultTransactionStatus status) throws Transac @Override protected void doCleanupAfterCompletion(Object transaction) { OrientTransaction tx = (OrientTransaction) transaction; - + if (!tx.getDatabase().isClosed()) { log.debug("closing transaction, db.hashCode() = {}", tx.getDatabase().hashCode()); tx.getDatabase().close(); } - + TransactionSynchronizationManager.unbindResource(dbf); } - + /* (non-Javadoc) * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#doSuspend(java.lang.Object) */ @@ -143,7 +147,7 @@ protected Object doSuspend(Object transaction) throws TransactionException { return tx.getDatabase(); } - + /* (non-Javadoc) * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#doResume(java.lang.Object, java.lang.Object) */ @@ -151,7 +155,7 @@ protected Object doSuspend(Object transaction) throws TransactionException { protected void doResume(Object transaction, Object suspendedResources) throws TransactionException { OrientTransaction tx = (OrientTransaction) transaction; ODatabase db = tx.getDatabase(); - + if (!db.isClosed()) { db.close(); } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/OrientRepository.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/OrientRepository.java index 1472451..795600d 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/OrientRepository.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/OrientRepository.java @@ -1,6 +1,7 @@ package org.springframework.data.orient.commons.repository; import org.springframework.data.domain.Sort; +import org.springframework.data.orient.commons.repository.annotation.Detach; import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.PagingAndSortingRepository; diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Cluster.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Cluster.java index 120f721..18b7d74 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Cluster.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Cluster.java @@ -4,7 +4,7 @@ /** * The annotation to declare orient cluster. - * + * * @author Dzmitry_Naskou */ @Documented diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Detach.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Detach.java index 5b3ce79..2fef06f 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Detach.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Detach.java @@ -6,7 +6,7 @@ @Documented @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Detach { DetachMode value(); diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/FetchPlan.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/FetchPlan.java index 2f9ce23..9bb8fa3 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/FetchPlan.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/FetchPlan.java @@ -4,7 +4,7 @@ @Documented @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface FetchPlan { String value(); diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Query.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Query.java index 17d1c7d..6682b68 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Query.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Query.java @@ -4,7 +4,7 @@ /** * The annotation to declare custom queries directly on repository methods. - * + * * @author Dzmitry_Naskou */ @Documented @@ -16,7 +16,7 @@ * Defines the Orient query to be executed when the annotated method is called. */ String value() default ""; - + /** * Defines a special count query that shall be used for pagination queries to lookup the total number of elements for * a page. If non is configured we will derive the count query from the method name. diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Source.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Source.java index d2b28bc..8976efa 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Source.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/annotation/Source.java @@ -6,7 +6,7 @@ /** * The annotation to declare orient source (class or cluster). - * + * * @author Dzmitry_Naskou */ @Documented @@ -20,7 +20,7 @@ * @return the source type */ SourceType type() default SourceType.CLUSTER; - + /** * Defines the Orient cluster name. */ diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/config/OrientRepositoryRegistrar.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/config/OrientRepositoryRegistrar.java index ac0768f..2cda111 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/config/OrientRepositoryRegistrar.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/config/OrientRepositoryRegistrar.java @@ -6,7 +6,7 @@ import java.lang.annotation.Annotation; /** - * {@link ImportBeanDefinitionRegistrar} to enable {@link EnableOrientRepositories} annotation. + * {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} to enable {@link EnableOrientRepositories} annotation. * * @author Dzmitry_Naskou */ diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/AbstractOrientQuery.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/AbstractOrientQuery.java index 3208274..478693d 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/AbstractOrientQuery.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/AbstractOrientQuery.java @@ -1,12 +1,10 @@ package org.springframework.data.orient.commons.repository.query; +import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLQuery; import org.springframework.data.orient.commons.core.OrientOperations; import org.springframework.data.orient.commons.repository.DetachMode; -import org.springframework.data.orient.commons.repository.query.OrientQueryExecution.CollectionExecution; -import org.springframework.data.orient.commons.repository.query.OrientQueryExecution.CountExecution; -import org.springframework.data.orient.commons.repository.query.OrientQueryExecution.PagedExecution; -import org.springframework.data.orient.commons.repository.query.OrientQueryExecution.SingleEntityExecution; +import org.springframework.data.orient.commons.repository.query.OrientQueryExecution.*; import org.springframework.data.repository.query.RepositoryQuery; /** @@ -14,16 +12,20 @@ */ public abstract class AbstractOrientQuery implements RepositoryQuery { - /** The query method. */ + /** + * The query method. + */ private final OrientQueryMethod method; - /** The object operations. */ + /** + * The object operations. + */ private final OrientOperations operations; /** * Instantiates a new {@link AbstractOrientQuery}. * - * @param method the query method + * @param method the query method * @param operations the orient operations */ public AbstractOrientQuery(OrientQueryMethod method, OrientOperations operations) { @@ -46,18 +48,18 @@ public OrientQueryMethod getQueryMethod() { public Object execute(Object[] parameters) { return doExecute(getExecution(), parameters); } - + /** * Do execute. * * @param execution the execution - * @param values the values + * @param values the values * @return the object */ protected Object doExecute(OrientQueryExecution execution, Object[] values) { return execution.execute(this, getDetachMode(), values); } - + /** * Creates the orient query. * @@ -68,7 +70,19 @@ protected Object doExecute(OrientQueryExecution execution, Object[] values) { protected OSQLQuery createQuery(Object[] values) { return applyFetchPlan(doCreateQuery(values)); } - + + /** + * Creates the orient command. + * + * @param values the parameters for query + * @return the OSQL query + */ + @SuppressWarnings("rawtypes") + protected OCommandSQL createCommand(Object[] values) { + return doCreateCommand(values); + } + + /** * Creates the count query. * @@ -79,7 +93,7 @@ protected OSQLQuery createQuery(Object[] values) { protected OSQLQuery createCountQuery(Object[] values) { return doCreateCountQuery(values); } - + /** * Do create query for specific source. * @@ -88,7 +102,7 @@ protected OSQLQuery createCountQuery(Object[] values) { */ @SuppressWarnings("rawtypes") protected abstract OSQLQuery doCreateQuery(Object[] values); - + /** * Do create count query for specific source. * @@ -97,7 +111,16 @@ protected OSQLQuery createCountQuery(Object[] values) { */ @SuppressWarnings("rawtypes") protected abstract OSQLQuery doCreateCountQuery(Object[] values); - + + /** + * Do create count query for specific source. + * + * @param values the parameters for query + * @return the OSQL Command + */ + + protected abstract OCommandSQL doCreateCommand(Object[] values); + /** * Gets the execution for query. * @@ -105,7 +128,7 @@ protected OSQLQuery createCountQuery(Object[] values) { */ protected OrientQueryExecution getExecution() { final OrientParameters parameters = method.getParameters(); - + if (method.isCollectionQuery()) { return new CollectionExecution(operations, parameters); } else if (isCountQuery()) { @@ -114,26 +137,30 @@ protected OrientQueryExecution getExecution() { return new PagedExecution(operations, parameters); } else if (method.isQueryForEntity()) { return new SingleEntityExecution(operations, parameters); - } - + } else if (isDeleteQuery()) { + return new DeleteExecution(operations, parameters); + } + throw new IllegalArgumentException(); } - + /** * Checks if is count query. * * @return true, if is count query */ protected abstract boolean isCountQuery(); - + + protected abstract boolean isDeleteQuery(); + @SuppressWarnings("rawtypes") private OSQLQuery applyFetchPlan(OSQLQuery query) { String fetchPlan = method.getFetchPlan(); - + if (fetchPlan != null) { query.setFetchPlan(fetchPlan); } - + return query; } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/JooqUtils.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/JooqUtils.java index b1ce880..305fe2f 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/JooqUtils.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/JooqUtils.java @@ -9,7 +9,7 @@ public class JooqUtils { public static DSLContext context() { - return DSL.using(SQLDialect.MYSQL); + return DSL.using(SQLDialect.DEFAULT); } public static SelectJoinStep from(String source) { diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryCreator.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryCreator.java index f534f33..5927823 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryCreator.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryCreator.java @@ -25,30 +25,31 @@ import java.util.List; import static org.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.table; public class OrientQueryCreator extends AbstractQueryCreator { - + private static final Logger logger = LoggerFactory.getLogger(OrientQueryCreator.class); - + private final DSLContext context; - + private final PartTree tree; - + private final OrientParameterAccessor accessor; - + private final OrientQueryMethod method; - + private final ParamType paramType; - + private final Class domainClass; - + public OrientQueryCreator(PartTree tree, OrientQueryMethod method, OrientParameterAccessor parameters) { this(tree, method, parameters, ParamType.NAMED); } public OrientQueryCreator(PartTree tree, OrientQueryMethod method, OrientParameterAccessor parameters, ParamType paramType) { super(tree, parameters); - + this.method = method; this.context = DSL.using(SQLDialect.MYSQL); this.tree = tree; @@ -56,7 +57,7 @@ public OrientQueryCreator(PartTree tree, OrientQueryMethod method, OrientParamet this.paramType = paramType; this.domainClass = method.getEntityInformation().getJavaType(); } - + @Override protected Condition create(Part part, Iterator iterator) { return toCondition(part, iterator); @@ -71,17 +72,27 @@ protected Condition and(Part part, Condition base, Iterator iterator) { protected Condition or(Condition base, Condition criteria) { return base.or(criteria); } - + public boolean isCountQuery() { return tree.isCountProjection(); } + public boolean isDeleteQuery() { + return tree.isDelete(); + } + @Override protected String complete(Condition criteria, Sort sort) { Pageable pageable = accessor.getPageable(); - + + + if (tree.isDelete()) { + return completeDelete(criteria, sort); + } + + SelectSelectStep selectStep; - + if (isCountQuery()) { selectStep = context.selectCount(); } else if (tree.isDistinct()) { @@ -90,7 +101,7 @@ protected String complete(Condition criteria, Sort sort) { selectStep = context.select(); } - SelectConditionStep conditionStep = selectStep.from(QueryUtils.toSource(getSource())).where(criteria); + SelectConditionStep conditionStep = selectStep.from(QueryUtils.toSource(getSource())).where(criteria); SelectLimitStep limitStep = orderByIfRequired(conditionStep, pageable, sort); @@ -101,51 +112,76 @@ protected String complete(Condition criteria, Sort sort) { //Use inline parameters for paged queries String queryString = query.getSQL(ParamType.INLINED); logger.debug(queryString); - + return queryString; } - + + private String completeDelete(Condition criteria, Sort sort) { + return context.deleteFrom(table(QueryUtils.toSource(getSource()))).where(criteria).getSQL(ParamType.INDEXED); + + + } + protected Condition toCondition(Part part, Iterator iterator) { String property = part.getProperty().toDotPath(); Field field = field(property); - + switch (part.getType()) { - case AFTER: - case GREATER_THAN: return field.gt(iterator.next()); - case GREATER_THAN_EQUAL: return field.ge(iterator.next()); + case AFTER: + case GREATER_THAN: + return field.gt(iterator.next()); + case GREATER_THAN_EQUAL: + return field.ge(iterator.next()); case BEFORE: - case LESS_THAN: return field.lt(iterator.next()); - case LESS_THAN_EQUAL: return field.le(iterator.next()); - case BETWEEN: return field.between(iterator.next(), iterator.next()); - case IS_NULL: return field.isNull(); - case IS_NOT_NULL: return field.isNotNull(); - case IN: return field.in(toList(iterator)); - case NOT_IN: return field.notIn(toList(iterator)); - case LIKE: return lowerIfIgnoreCase(part, field, iterator); - case NOT_LIKE: return lowerIfIgnoreCase(part, field, iterator).not(); - case STARTING_WITH: return field.startsWith(iterator.next()); - case ENDING_WITH: return field.endsWith(iterator.next()); - case CONTAINING: return field.contains(iterator.next()); - case SIMPLE_PROPERTY: return field.eq(iterator.next()); - case NEGATING_SIMPLE_PROPERTY: return field.ne(iterator.next()); - case TRUE: return field.eq(true); - case FALSE: return field.eq(false); - default: throw new IllegalArgumentException("Unsupported keyword!"); + case LESS_THAN: + return field.lt(iterator.next()); + case LESS_THAN_EQUAL: + return field.le(iterator.next()); + case BETWEEN: + return field.between(iterator.next(), iterator.next()); + case IS_NULL: + return field.isNull(); + case IS_NOT_NULL: + return field.isNotNull(); + case IN: + return field.in(toList(iterator)); + case NOT_IN: + return field.notIn(toList(iterator)); + case LIKE: + return lowerIfIgnoreCase(part, field, iterator); + case NOT_LIKE: + return lowerIfIgnoreCase(part, field, iterator).not(); + case STARTING_WITH: + return field.startsWith(iterator.next()); + case ENDING_WITH: + return field.endsWith(iterator.next()); + case CONTAINING: + return field.contains(iterator.next()); + case SIMPLE_PROPERTY: + return field.eq(iterator.next()); + case NEGATING_SIMPLE_PROPERTY: + return field.ne(iterator.next()); + case TRUE: + return field.eq(true); + case FALSE: + return field.eq(false); + default: + throw new IllegalArgumentException("Unsupported keyword!"); } } - + protected OrientSource getSource() { OrientSource orientSource = accessor.getSource(); - + if (orientSource != null) { return orientSource; } - + Source source = findAnnotation(Source.class); if (source != null) { return new DefaultSource(source.type(), source.value()); } - + Cluster cluster = findAnnotation(Cluster.class); if (cluster != null) { return new DefaultSource(cluster.value()); @@ -153,67 +189,77 @@ protected OrientSource getSource() { return new DefaultSource(domainClass); } - + @SuppressWarnings("incomplete-switch") private Condition lowerIfIgnoreCase(Part part, Field field, Iterator iterator) { switch (part.shouldIgnoreCase()) { case ALWAYS: - case WHEN_POSSIBLE: return field.likeIgnoreCase(iterator.next().toString()); + case WHEN_POSSIBLE: + return field.likeIgnoreCase(iterator.next().toString()); } - + return field.like(iterator.next().toString()); } - + private List toList(Iterator iterator) { if (iterator == null || !iterator.hasNext()) { return Collections.emptyList(); } - + List list = new ArrayList(); while (iterator.hasNext()) { list.add(iterator.next()); } - + return list; } - + private List> toOrders(Sort sort) { List> orders = new ArrayList>(); - + for (Order order : sort) { - orders.add(field(order.getProperty()).sort(order.getDirection() == Direction.ASC ? SortOrder.ASC : SortOrder.DESC)); + orders.add(field(order.getProperty()).sort(order.getDirection() == Direction.ASC ? SortOrder.ASC : SortOrder.DESC)); } return orders; } - + private SelectLimitStep orderByIfRequired(SelectConditionStep conditionStep, Pageable pageable, Sort sort) { if (isCountQuery()) { return conditionStep; - } if (sort == null) { + } + + + if (sort == null) { return pageable == null ? conditionStep : conditionStep.and(field("@rid").gt(pageable.getOffset())); - } else { - return conditionStep.orderBy(toOrders(sort)); } + + +// if (sort == null) { +// return conditionStep; +// } + return conditionStep.orderBy(toOrders(sort)); + } - + private Query limitIfPageable(SelectLimitStep limitStep, Pageable pageable, Sort sort) { if (pageable == null || isCountQuery()) { return limitStep; } else if (sort == null) { return limitStep.limit(pageable.getPageSize()); - } else { - return limitStep.limit(pageable.getPageSize()).offset(pageable.getOffset()); } + + return limitStep.limit(pageable.getPageSize()).offset(pageable.getOffset()); + } - + private A findAnnotation(Class annotationType) { A annotation = AnnotationUtils.findAnnotation(method.getMethod(), annotationType); - + if (annotation == null) { annotation = AnnotationUtils.findAnnotation(method.getRepositoryInterface(), annotationType); } - + return annotation; } } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryExecution.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryExecution.java index 34439b8..0e23340 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryExecution.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryExecution.java @@ -10,17 +10,20 @@ import java.util.List; /** - * Set of classes to contain query execution strategies. - * + * Set of classes to contain query execution strategies. + * * @author Dzmitry_Naskou - * */ public abstract class OrientQueryExecution { - /** The orient object template. */ + /** + * The orient object template. + */ protected final OrientOperations operations; - - /** The parameters. */ + + /** + * The parameters. + */ protected final OrientParameters parameters; public OrientQueryExecution(OrientOperations template, OrientParameters parameters) { @@ -28,30 +31,45 @@ public OrientQueryExecution(OrientOperations template, OrientParameters paramete this.operations = template; this.parameters = parameters; } - + /** * Executes the given {@link AbstractOrientQuery} with the given {@link Object[]} values. * - * @param query the orient query + * @param query the orient query * @param values the parameters values * @return the result */ public Object execute(AbstractOrientQuery query, DetachMode mode, Object[] values) { return doExecute(query, mode, values); } - + /** * Method to implement by executions. * - * @param query the orient query + * @param query the orient query * @param values the parameters values * @return the result */ protected abstract Object doExecute(AbstractOrientQuery query, DetachMode mode, Object[] values); - + + protected Object[] prepareParameters(OrientParameters parameters, Object[] values) { + int index = 0; + List params = new ArrayList<>(); + + for (OrientParameter parameter : parameters) { + if (parameter.isBindable()) { + params.add(values[index]); + } + + ++index; + } + + return params.toArray(); + } + /** * Executes the query to return a simple collection of entities. - * + * * @author Dzmitry_Naskou */ static class CollectionExecution extends OrientQueryExecution { @@ -136,7 +154,7 @@ static class PagedExecution extends OrientQueryExecution { /** * Instantiates a new {@link PagedExecution}. * - * @param template the orient object template + * @param template the orient object template * @param parameters the parameters */ public PagedExecution(OrientOperations template, OrientParameters parameters) { @@ -150,37 +168,34 @@ public PagedExecution(OrientOperations template, OrientParameters parameters) { @SuppressWarnings("unchecked") protected Object doExecute(AbstractOrientQuery query, DetachMode mode, Object[] values) { OrientParameterAccessor accessor = new OrientParametersParameterAccessor(parameters, values); - + final Object[] queryParams = prepareParameters(parameters, values); - + Long total = operations.count(query.createCountQuery(values), queryParams); - + Pageable pageable = accessor.getPageable(); - + List content; - + if (pageable != null && total > pageable.getOffset()) { content = operations.query(query.createQuery(values), mode, queryParams); } else { content = Collections.emptyList(); } - + return new PageImpl<>(content, pageable, total); } } - - protected Object[] prepareParameters(OrientParameters parameters, Object[] values) { - int index = 0; - List params = new ArrayList<>(); - - for (OrientParameter parameter : parameters) { - if (parameter.isBindable()) { - params.add(values[index]); - } - - ++index; + + static class DeleteExecution extends OrientQueryExecution { + + public DeleteExecution(OrientOperations template, OrientParameters parameters) { + super(template, parameters); + } + + @Override + protected Object doExecute(AbstractOrientQuery query, DetachMode mode, Object[] values) { + return operations.command(query.createCommand(values), prepareParameters(parameters, values)); } - - return params.toArray(); } } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryLookupStrategy.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryLookupStrategy.java index 3745f78..1866aff 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryLookupStrategy.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryLookupStrategy.java @@ -1,18 +1,38 @@ package org.springframework.data.orient.commons.repository.query; import org.springframework.data.orient.commons.core.OrientOperations; +import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.repository.core.NamedQueries; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.query.QueryLookupStrategy; import org.springframework.data.repository.query.QueryLookupStrategy.Key; import org.springframework.data.repository.query.RepositoryQuery; +import java.lang.reflect.Method; + public final class OrientQueryLookupStrategy { private OrientQueryLookupStrategy() { super(); } + public static QueryLookupStrategy create(OrientOperations operations, Key key) { + if (key == null) { + return new CreateIfNotFoundQueryLookupStrategy(operations); + } + + switch (key) { + case CREATE: + return new CreateQueryLookupStrategy(operations); + case USE_DECLARED_QUERY: + return new DeclaredQueryLookupStrategy(operations); + case CREATE_IF_NOT_FOUND: + return new CreateIfNotFoundQueryLookupStrategy(operations); + default: + throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key)); + } + } + private abstract static class AbstractQueryLookupStrategy implements QueryLookupStrategy { private final OrientOperations operations; @@ -23,14 +43,14 @@ public AbstractQueryLookupStrategy(OrientOperations template) { /* * (non-Javadoc) - * + * * @see org.springframework.data.repository.query.QueryLookupStrategy# * resolveQuery(java.lang.reflect.Method, * org.springframework.data.repository.core.RepositoryMetadata, * org.springframework.data.repository.core.NamedQueries) */ - public final RepositoryQuery resolveQuery(java.lang.reflect.Method method, RepositoryMetadata metadata, NamedQueries namedQueries) { - return resolveQuery(new OrientQueryMethod(method, metadata), operations, namedQueries); + public final RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory, NamedQueries namedQueries) { + return resolveQuery(new OrientQueryMethod(method, metadata,factory), operations, namedQueries); } protected abstract RepositoryQuery resolveQuery(OrientQueryMethod method, OrientOperations template, NamedQueries namedQueries); @@ -41,7 +61,7 @@ private static class CreateQueryLookupStrategy extends AbstractQueryLookupStrate /** * Instantiates a new {@link CreateQueryLookupStrategy} lookup strategy. * - * @param db the application database service + * @param template the application database service */ public CreateQueryLookupStrategy(OrientOperations template) { super(template); @@ -88,10 +108,14 @@ protected RepositoryQuery resolveQuery(OrientQueryMethod method, OrientOperation private static class CreateIfNotFoundQueryLookupStrategy extends AbstractQueryLookupStrategy { - /** The declared query strategy. */ + /** + * The declared query strategy. + */ private final DeclaredQueryLookupStrategy strategy; - /** The create query strategy. */ + /** + * The create query strategy. + */ private final CreateQueryLookupStrategy createStrategy; /** @@ -118,21 +142,4 @@ protected RepositoryQuery resolveQuery(OrientQueryMethod method, OrientOperation } } - public static QueryLookupStrategy create(OrientOperations operations, Key key) { - if (key == null) { - return new CreateIfNotFoundQueryLookupStrategy(operations); - } - - switch (key) { - case CREATE: - return new CreateQueryLookupStrategy(operations); - case USE_DECLARED_QUERY: - return new DeclaredQueryLookupStrategy(operations); - case CREATE_IF_NOT_FOUND: - return new CreateIfNotFoundQueryLookupStrategy(operations); - default: - throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key)); - } - } - } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryMethod.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryMethod.java index 22d2f1d..789b102 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryMethod.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/OrientQueryMethod.java @@ -1,10 +1,11 @@ package org.springframework.data.orient.commons.repository.query; import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.data.orient.commons.repository.annotation.Detach; import org.springframework.data.orient.commons.repository.DetachMode; +import org.springframework.data.orient.commons.repository.annotation.Detach; import org.springframework.data.orient.commons.repository.annotation.FetchPlan; import org.springframework.data.orient.commons.repository.annotation.Query; +import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.query.QueryMethod; import org.springframework.util.StringUtils; @@ -18,24 +19,28 @@ */ public final class OrientQueryMethod extends QueryMethod { - /** The method. */ + /** + * The method. + */ private final Method method; - /** The repository interface. */ + /** + * The repository interface. + */ private final Class repositoryInterface; /** * Instantiates a new {@link OrientQueryMethod}. * - * @param method the method + * @param method the method * @param metadata the metadata */ - public OrientQueryMethod(Method method, RepositoryMetadata metadata) { - super(method, metadata); + public OrientQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory) { + super(method, metadata, factory); this.method = method; this.repositoryInterface = metadata.getRepositoryInterface(); } - + /* (non-Javadoc) * @see org.springframework.data.repository.query.QueryMethod#createParameters(java.lang.reflect.Method) */ @@ -69,13 +74,13 @@ public Class getRepositoryInterface() { /** * Returns whether the method has an annotated query. - * + * * @return */ public boolean hasAnnotatedQuery() { return getAnnotatedQuery() != null; } - + /** * Returns the query string declared in a {@link Query} annotation or {@literal null} if neither the annotation found * nor the attribute was specified. @@ -86,33 +91,33 @@ String getAnnotatedQuery() { String query = (String) AnnotationUtils.getValue(getQueryAnnotation()); return StringUtils.hasText(query) ? query : null; } - + /** * Returns the {@link Query} annotation that is applied to the method or {@code null} if none available. - * + * * @return */ Query getQueryAnnotation() { return method.getAnnotation(Query.class); } - + FetchPlan getFetchPlanAnnotation() { return method.getAnnotation(FetchPlan.class); } - + String getFetchPlan() { String plan = (String) AnnotationUtils.getValue(getFetchPlanAnnotation()); - + return StringUtils.hasText(plan) ? plan : null; } - + Detach getDetachAnnotation() { return method.getAnnotation(Detach.class); } - + DetachMode getDetachMode() { DetachMode mode = (DetachMode) AnnotationUtils.getValue(getDetachAnnotation()); - + return mode == null ? DetachMode.NONE : mode; } } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/PartTreeOrientQuery.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/PartTreeOrientQuery.java index 3d54db3..99be70b 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/PartTreeOrientQuery.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/PartTreeOrientQuery.java @@ -1,5 +1,6 @@ package org.springframework.data.orient.commons.repository.query; +import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import org.springframework.data.orient.commons.core.OrientOperations; @@ -12,13 +13,19 @@ */ public class PartTreeOrientQuery extends AbstractOrientQuery { - /** The domain class. */ + /** + * The domain class. + */ private final Class domainClass; - /** The tree. */ + /** + * The tree. + */ private final PartTree tree; - /** The parameters. */ + /** + * The parameters. + */ private final OrientParameters parameters; private final OrientQueryMethod method; @@ -26,7 +33,7 @@ public class PartTreeOrientQuery extends AbstractOrientQuery { /** * Instantiates a new {@link PartTreeOrientQuery} from given {@link OrientQueryMethod} and {@link OrientOperations}. * - * @param method the query method + * @param method the query method * @param operations the orient object template */ public PartTreeOrientQuery(OrientQueryMethod method, OrientOperations operations) { @@ -45,9 +52,9 @@ public PartTreeOrientQuery(OrientQueryMethod method, OrientOperations operations @SuppressWarnings("rawtypes") protected OSQLQuery doCreateQuery(Object[] values) { OrientParameterAccessor accessor = new OrientParametersParameterAccessor(parameters, values); - + OrientQueryCreator creator = new OrientQueryCreator(tree, method, accessor); - + return new OSQLSynchQuery(creator.createQuery()); } @@ -58,12 +65,21 @@ protected OSQLQuery doCreateQuery(Object[] values) { @SuppressWarnings("rawtypes") protected OSQLQuery doCreateCountQuery(Object[] values) { OrientParameterAccessor accessor = new OrientParametersParameterAccessor(parameters, values); - + OrientQueryCreator creator = new OrientCountQueryCreator(tree, method, accessor); - + return new OSQLSynchQuery(creator.createQuery()); } + @Override + protected OCommandSQL doCreateCommand(Object[] values) { + OrientParameterAccessor accessor = new OrientParametersParameterAccessor(parameters, values); + + OrientQueryCreator creator = new OrientQueryCreator(tree, method, accessor); + + return new OCommandSQL(creator.createQuery()); + } + /* (non-Javadoc) * @see org.springframework.data.orient.repository.object.query.AbstractOrientQuery#isCountQuery() */ @@ -71,4 +87,9 @@ protected OSQLQuery doCreateCountQuery(Object[] values) { protected boolean isCountQuery() { return tree.isCountProjection(); } + + @Override + protected boolean isDeleteQuery() { + return tree.isDelete(); + } } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/StringBasedOrientQuery.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/StringBasedOrientQuery.java index 847bdcf..c56eda8 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/StringBasedOrientQuery.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/StringBasedOrientQuery.java @@ -1,20 +1,24 @@ package org.springframework.data.orient.commons.repository.query; import com.orientechnologies.orient.core.record.impl.ODocument; +import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import org.springframework.data.orient.commons.core.OrientOperations; public class StringBasedOrientQuery extends AbstractOrientQuery { - + private final String queryString; - + private final boolean isCountQuery; - + private final boolean isDeleteQuery; + public StringBasedOrientQuery(String query, OrientQueryMethod method, OrientOperations operations) { super(method, operations); this.queryString = query; this.isCountQuery = method.hasAnnotatedQuery() ? method.getQueryAnnotation().count() : false; + isDeleteQuery = query.toLowerCase().contains("delete"); + } @Override @@ -22,7 +26,7 @@ public StringBasedOrientQuery(String query, OrientQueryMethod method, OrientOper protected OSQLQuery doCreateQuery(Object[] values) { OrientParameterAccessor accessor = new OrientParametersParameterAccessor(getQueryMethod().getParameters(), values); String sortedQuery = QueryUtils.applySorting(queryString, accessor.getSort()); - + return new OSQLSynchQuery(sortedQuery); } @@ -32,8 +36,21 @@ protected OSQLQuery doCreateCountQuery(Object[] values) { return new OSQLSynchQuery(queryString); } + @Override + protected OCommandSQL doCreateCommand(Object[] values) { + OrientParameterAccessor accessor = new OrientParametersParameterAccessor(getQueryMethod().getParameters(), values); + String sortedQuery = QueryUtils.applySorting(queryString, accessor.getSort()); + + return new OCommandSQL(sortedQuery); + } + @Override protected boolean isCountQuery() { return this.isCountQuery; } + + @Override + protected boolean isDeleteQuery() { + return isDeleteQuery; + } } diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/OrientRepositoryFactory.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/OrientRepositoryFactory.java index 5b81d93..45ca505 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/OrientRepositoryFactory.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/OrientRepositoryFactory.java @@ -10,6 +10,7 @@ import org.springframework.data.repository.core.RepositoryInformation; import org.springframework.data.repository.core.RepositoryMetadata; 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.data.repository.query.QueryLookupStrategy.Key; diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/OrientRepositoryFactoryBean.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/OrientRepositoryFactoryBean.java index 712aa20..423ec87 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/OrientRepositoryFactoryBean.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/OrientRepositoryFactoryBean.java @@ -24,6 +24,15 @@ public class OrientRepositoryFactoryBean, S, ID exte @Autowired private OrientOperations operations; + /** + * Creates a new {@link TransactionalRepositoryFactoryBeanSupport} for the given repository interface. + * + * @param repositoryInterface must not be {@literal null}. + */ + protected OrientRepositoryFactoryBean(Class repositoryInterface) { + super(repositoryInterface); + } + /* (non-Javadoc) * @see org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport#doCreateRepositoryFactory() */ diff --git a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/SimpleOrientRepository.java b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/SimpleOrientRepository.java index a2aa3aa..122a9b9 100644 --- a/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/SimpleOrientRepository.java +++ b/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/support/SimpleOrientRepository.java @@ -339,6 +339,7 @@ private OSQLQuery getQuery(Sort sort) { * @return the query */ private OSQLQuery getQuery(String source, Sort sort) { + Query query = DSL.using(SQLDialect.MYSQL).select().from(source).orderBy(QueryUtils.toOrders(sort)); return new OSQLSynchQuery(query.getSQL(ParamType.INLINED)); diff --git a/spring-data-orientdb-commons/src/test/java/org/springframework/data/orient/commons/repository/config/OrientPackageScannerTest.java b/spring-data-orientdb-commons/src/test/java/org/springframework/data/orient/commons/repository/config/OrientPackageScannerTest.java index ffb676d..23191f9 100644 --- a/spring-data-orientdb-commons/src/test/java/org/springframework/data/orient/commons/repository/config/OrientPackageScannerTest.java +++ b/spring-data-orientdb-commons/src/test/java/org/springframework/data/orient/commons/repository/config/OrientPackageScannerTest.java @@ -1,12 +1,15 @@ package org.springframework.data.orient.commons.repository.config; -import org.springframework.data.orient.commons.repository.config.scanner.test.*; -import org.testng.annotations.Test; +import org.junit.Test; +import org.springframework.data.orient.commons.repository.config.scanner.test.EntitiesMarker; +import org.springframework.data.orient.commons.repository.config.scanner.test.SimpleEdgeEntity; +import org.springframework.data.orient.commons.repository.config.scanner.test.SimpleVertexEntity; import java.util.HashSet; import java.util.Set; -import static org.testng.Assert.assertEquals; +import static org.junit.Assert.assertEquals; + /** * @author saljuama diff --git a/spring-data-orientdb-document/pom.xml b/spring-data-orientdb-document/pom.xml index 068b7b2..77a404a 100644 --- a/spring-data-orientdb-document/pom.xml +++ b/spring-data-orientdb-document/pom.xml @@ -1,13 +1,11 @@ - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT ../pom.xml @@ -18,7 +16,7 @@ - org.springframework.data + com.orientechnologies spring-data-orientdb-commons ${project.version} diff --git a/spring-data-orientdb-document/src/main/java/org/springframework/data/orient/document/OrientDocumentDatabaseFactory.java b/spring-data-orientdb-document/src/main/java/org/springframework/data/orient/document/OrientDocumentDatabaseFactory.java index f1a767e..7806432 100644 --- a/spring-data-orientdb-document/src/main/java/org/springframework/data/orient/document/OrientDocumentDatabaseFactory.java +++ b/spring-data-orientdb-document/src/main/java/org/springframework/data/orient/document/OrientDocumentDatabaseFactory.java @@ -3,7 +3,6 @@ import com.orientechnologies.orient.core.db.OPartitionedDatabasePool; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.impl.ODocument; import org.springframework.data.orient.commons.core.AbstractOrientDatabaseFactory; /** @@ -21,7 +20,7 @@ public class OrientDocumentDatabaseFactory extends AbstractOrientDatabaseFactory @Override protected void createPool() { - pool = new OPartitionedDatabasePool(getUrl(), getUsername(), getPassword(), maxPoolSize); + pool = new OPartitionedDatabasePool(getUrl(), getUsername(), getPassword(), maxPoolSize, -1); } /* (non-Javadoc) diff --git a/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/Address.java b/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/Address.java new file mode 100644 index 0000000..a7cbaec --- /dev/null +++ b/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/Address.java @@ -0,0 +1,51 @@ +package org.springframework.data.orient.document.repository; + +import com.orientechnologies.orient.core.annotation.OId; +import com.orientechnologies.orient.core.annotation.OVersion; + +public class Address { + + @OId + private String id; + + @OVersion + private Long version; + + private String country; + + private String city; + + private String street; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } +} diff --git a/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/Person.java b/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/Person.java new file mode 100644 index 0000000..744c8ee --- /dev/null +++ b/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/Person.java @@ -0,0 +1,61 @@ +package org.springframework.data.orient.document.repository; + +import com.orientechnologies.orient.core.annotation.OId; +import com.orientechnologies.orient.core.annotation.OVersion; + +public class Person { + + @OId + private String rid; + + @OVersion + private Long version; + + private String firstName; + + private String lastName; + + private Address address; + + private Boolean active; + + public String getRid() { + return rid; + } + + public void setRid(String rid) { + this.rid = rid; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public Boolean getActive() { + return active; + } + + public void setActive(Boolean active) { + this.active = active; + } +} diff --git a/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/PersonRepository.java b/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/PersonRepository.java new file mode 100644 index 0000000..bafe5bb --- /dev/null +++ b/spring-data-orientdb-document/src/test/java/org/springframework/data/orient/document/repository/PersonRepository.java @@ -0,0 +1,55 @@ +package org.springframework.data.orient.document.repository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.orient.commons.repository.DetachMode; +import org.springframework.data.orient.commons.repository.annotation.Detach; +import org.springframework.data.orient.commons.repository.annotation.FetchPlan; +import org.springframework.data.orient.commons.repository.annotation.Query; + +import java.util.List; + +public interface PersonRepository extends OrientDocumentRepository { + + @Query("select from person where firstName = ?") + List findByFirstName(String firstName); + + Page findByFirstName(String firstName, Pageable pageable); + + List findByLastName(String lastName); + + List findByLastNameLike(String lastName); + + List findByFirstNameAndLastName(String firstName, String lastName); + + List findByFirstNameOrLastName(String firstName, String lastName); + + List findByFirstNameLike(String string); + + List findByFirstNameStartsWith(String firstName); + + Long countByFirstName(String firstName); + + Long countByActive(Boolean active); + + @Query(value = "select count(*) from person where firstName = ? and active = ?", count = true) + Long countByFirstNameAndActive(String firstName, Boolean active); + + @Detach(DetachMode.ENTITY) + List findByAddress_City(String city); + + @FetchPlan("*:-1") + List findByAddress_Country(String city); + + List findByActiveIsTrue(); + + List findByActiveIsFalse(); + + Long deleteByActiveIsTrue(); + + Long deleteByActiveIsFalse(); + + Long deleteByActive(Boolean active); + + +} diff --git a/spring-data-orientdb-graph/pom.xml b/spring-data-orientdb-graph/pom.xml index 0d35e93..90a054c 100644 --- a/spring-data-orientdb-graph/pom.xml +++ b/spring-data-orientdb-graph/pom.xml @@ -1,13 +1,11 @@ - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT ../pom.xml @@ -18,7 +16,7 @@ - org.springframework.data + com.orientechnologies spring-data-orientdb-commons ${project.version} diff --git a/spring-data-orientdb-object/pom.xml b/spring-data-orientdb-object/pom.xml index a1a619c..534a2a2 100644 --- a/spring-data-orientdb-object/pom.xml +++ b/spring-data-orientdb-object/pom.xml @@ -1,13 +1,11 @@ - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT ../pom.xml @@ -18,7 +16,7 @@ - org.springframework.data + com.orientechnologies spring-data-orientdb-commons ${project.version} diff --git a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectDatabaseFactory.java b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectDatabaseFactory.java index 7b72498..cf7661b 100644 --- a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectDatabaseFactory.java +++ b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectDatabaseFactory.java @@ -1,7 +1,10 @@ package org.springframework.data.orient.object; -import com.orientechnologies.orient.object.db.OObjectDatabasePool; +import com.orientechnologies.orient.core.db.OPartitionedDatabasePool; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.object.db.OObjectDatabaseTx; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.data.orient.commons.core.AbstractOrientDatabaseFactory; /** @@ -12,20 +15,28 @@ */ public class OrientObjectDatabaseFactory extends AbstractOrientDatabaseFactory { - private OObjectDatabasePool pool; + private static Logger log = LoggerFactory.getLogger(AbstractOrientDatabaseFactory.class); - /** The database. */ + private OPartitionedDatabasePool pool; + + /** + * The database. + */ private OObjectDatabaseTx db; @Override protected void createPool() { - pool = new OObjectDatabasePool(getUrl(), getUsername(), getPassword()); - pool.setup(minPoolSize, maxPoolSize); + //since max pool size was set, use it to create the partitioned pool + int maxPartitionSize = Runtime.getRuntime().availableProcessors(); + pool = new OPartitionedDatabasePool(getUrl(), getUsername(), getPassword(), + maxPartitionSize, maxPoolSize); } + @Override public OObjectDatabaseTx openDatabase() { - db = pool.acquire(); + ODatabaseDocumentTx documentTx = pool.acquire(); + db = new OObjectDatabaseTx(documentTx); return db; } diff --git a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectOperations.java b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectOperations.java index cda9cec..825fb6e 100644 --- a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectOperations.java +++ b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectOperations.java @@ -4,5 +4,6 @@ import org.springframework.data.orient.commons.core.OrientOperations; public interface OrientObjectOperations extends OrientOperations { + OObjectDatabaseTx getObjectDatabase(); } diff --git a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectTemplate.java b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectTemplate.java index 1987609..2f9f6e4 100644 --- a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectTemplate.java +++ b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/OrientObjectTemplate.java @@ -20,26 +20,26 @@ public OrientObjectTemplate(OrientObjectDatabaseFactory dbf) { @Override public OObjectDatabaseTx getObjectDatabase() { - return (OObjectDatabaseTx)dbf.db(); + return (OObjectDatabaseTx) dbf.db(); } @Override public String getRid(Object entity) { Class clazz = entity.getClass(); - while(clazz != Object.class){ - for(Field field : clazz.getDeclaredFields()){ + while (clazz != Object.class) { + for (Field field : clazz.getDeclaredFields()) { OId ridAnnotation = field.getAnnotation(OId.class); - if(ridAnnotation != null){ + if (ridAnnotation != null) { field.setAccessible(true); - try{ + try { Object rid = field.get(entity); - if(rid == null) { + if (rid == null) { Method method = clazz.getDeclaredMethod(getterName(field.getName())); rid = method.invoke(entity); } - return rid != null ? rid.toString() : null; + return rid != null ? rid.toString() : null; } catch (IllegalAccessException | IllegalArgumentException - | NoSuchMethodException | InvocationTargetException ex){ + | NoSuchMethodException | InvocationTargetException ex) { throw new RuntimeException(ex); } } @@ -65,7 +65,7 @@ public > RET detach(RET entities) { result.add(db.detach(entity, true)); } - return (RET)result; + return (RET) result; } @Override @@ -86,271 +86,14 @@ public > RET detachAll(RET entities) { @Override @SuppressWarnings("unchecked") public RET detach(RET entity) { - return (RET)getObjectDatabase().detach(entity, true); + return (RET) getObjectDatabase().detach(entity, true); } @Override @SuppressWarnings("unchecked") public RET detachAll(RET entity) { - return (RET)getObjectDatabase().detachAll(entity, true); - } - -/** - @Override - public > RET query(OQuery query, DetachMode detachMode, Object... args) { - RET result = query(query, args); - - switch (detachMode) { - case ENTITY: - return detach(result); - case ALL: - return detachAll(result); - case NONE: - } - - return result; - } - - @Override - @SuppressWarnings("unchecked") - public > RET detach(RET list) { - final OObjectDatabaseTx db = getObjectDatabase(); - - List pojos = new ArrayList<>(list.size()); - - for (Object object : list) { - pojos.add(db.detach(object, true)); - } - - return (RET) pojos; - } - - @Override - @SuppressWarnings("unchecked") - public > RET detachAll(RET list) { - final OObjectDatabaseTx db = getObjectDatabase(); - - List pojos = new ArrayList<>(list.size()); - - for (Object object : list) { - pojos.add(db.detachAll(object, true)); - } - - return (RET) pojos; - } - - @Override - public OObjectIteratorClass browseClass(Class iClusterClass) { - return getObjectDatabase().browseClass(iClusterClass); - } - - @Override - public OObjectIteratorClass browseClass(Class iClusterClass, boolean iPolymorphic) { - return getObjectDatabase().browseClass(iClusterClass, iPolymorphic); - } - - @Override - public OObjectIteratorClass browseClass(String iClassName) { - return getObjectDatabase().browseClass(iClassName); - } - - @Override - public OObjectIteratorClass browseClass(String iClassName, boolean iPolymorphic) { - return getObjectDatabase().browseClass(iClassName, iPolymorphic); - } - - @Override - public ODatabaseInternal getDatabaseOwner() { - return getObjectDatabase().getDatabaseOwner(); - } - - @Override - public ODatabaseInternal setDatabaseOwner(ODatabaseInternal iOwner) { - return getObjectDatabase().setDatabaseOwner(iOwner); - } - - @Override - public OObjectIteratorCluster browseCluster(String iClusterName) { - return getObjectDatabase().browseCluster(iClusterName); - } - - @Override - public V callInLock(Callable iCallable, boolean iExclusiveLock) { - return getObjectDatabase().callInLock(iCallable, iExclusiveLock); - } - - @Override - public ODatabasePojoAbstract setRetainObjects(boolean iValue) { - return getObjectDatabase().setRetainObjects(iValue); - } - - @Override - public void attach(Object iPojo) { - getObjectDatabase().attach(iPojo); - } - - @Override - public RET attachAndSave(Object iPojo) { - return getObjectDatabase().attachAndSave(iPojo); - } - - @Override - public boolean isRetainObjects() { - return getObjectDatabase().isRetainObjects(); - } - - @Override - public RET detach(Object iPojo) { - return getObjectDatabase().detach(iPojo); - } - - @Override - public RET detach(Object iPojo, boolean returnNonProxiedInstance) { - return getObjectDatabase().detach(iPojo, returnNonProxiedInstance); - } - - @Override - public boolean existsUserObjectByRID(ORID iRID) { - return getObjectDatabase().existsUserObjectByRID(iRID); - } - - @Override - public ODocument getRecordById(ORID iRecordId) { - return getObjectDatabase().getRecordById(iRecordId); - } - - @Override - public RET detachAll(Object iPojo, boolean returnNonProxiedInstance) { - return getObjectDatabase().detachAll(iPojo, returnNonProxiedInstance); - } - - @Override - public boolean isManaged(Object iEntity) { - return getObjectDatabase().isManaged(iEntity); - } - - @Override - public Object getUserObjectByRecord(OIdentifiable iRecord, String iFetchPlan) { - return dbf.db().getUserObjectByRecord(iRecord, iFetchPlan); - } - - @Override - public long countClass(String className) { - return getObjectDatabase().countClass(className); - } - - @Override - public long countClass(Class clazz) { - return getObjectDatabase().countClass(clazz); - } - - @Override - public OEntityManager getEntityManager() { - return getObjectDatabase().getEntityManager(); - } - - @Override - public ODatabaseDocument getUnderlying() { - return getObjectDatabase().getUnderlying(); - } - - @Override - public ORecordVersion getVersion(Object iPojo) { - return getObjectDatabase().getVersion(iPojo); - } - - @Override - public ORID getIdentity(Object iPojo) { - return getObjectDatabase().getIdentity(iPojo); - } - - @Override - public boolean isSaveOnlyDirty() { - return getObjectDatabase().isSaveOnlyDirty(); - } - - @Override - public void setSaveOnlyDirty(boolean saveOnlyDirty) { - getObjectDatabase().setSaveOnlyDirty(saveOnlyDirty); - } - - @Override - public boolean isAutomaticSchemaGeneration() { - return getObjectDatabase().isAutomaticSchemaGeneration(); - } - - @Override - public void setAutomaticSchemaGeneration(boolean automaticSchemaGeneration) { - getObjectDatabase().setAutomaticSchemaGeneration(automaticSchemaGeneration); - } - - @Override - public ODocument pojo2Stream(Object iPojo, ODocument iRecord) { - return getObjectDatabase().pojo2Stream(iPojo, iRecord); - } - - @Override - public Object stream2pojo(ODocument iRecord, Object iPojo, String iFetchPlan) { - return getObjectDatabase().stream2pojo(iRecord, iPojo, iFetchPlan); + return (RET) getObjectDatabase().detachAll(entity, true); } - @Override - public Object stream2pojo(ODocument iRecord, Object iPojo, String iFetchPlan, boolean iReload) { - return getObjectDatabase().stream2pojo(iRecord, iPojo, iFetchPlan, iReload); - } - @Override - public boolean isLazyLoading() { - return getObjectDatabase().isLazyLoading(); - } - - @Override - public void setLazyLoading(boolean lazyLoading) { - getObjectDatabase().setLazyLoading(lazyLoading); - } - - @Override - public void unregisterPojo(Object iObject, ODocument iRecord) { - getObjectDatabase().unregisterPojo(iObject, iRecord); - } - - @Override - public void registerClassMethodFilter(Class iClass, OObjectMethodFilter iMethodFilter) { - getObjectDatabase().registerClassMethodFilter(iClass, iMethodFilter); - } - - @Override - public void deregisterClassMethodFilter(Class iClass) { - getObjectDatabase().deregisterClassMethodFilter(iClass); - } - - @Override - public RET queryForObject(OSQLQuery query, Object... args) { - List list = query(query, args); - - return list.isEmpty() ? null : list.get(0); - } - - @Override - public RET queryForObject(OSQLQuery query, DetachMode detachMode, Object... args) { - RET result = queryForObject(query, args); - - switch (detachMode) { - case ENTITY: - return getObjectDatabase().detach(result, true); - case ALL: - return getObjectDatabase().detachAll(result, true); - case NONE: - } - - return result; - } - - @Override - public void registerEntityClass(Class domainClass) { - try (OObjectDatabaseTx db = getObjectDatabase()) { - db.getEntityManager().registerEntityClass(domainClass); - } - } - */ } diff --git a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/OrientObjectRepository.java b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/OrientObjectRepository.java index 011731a..2570cf7 100644 --- a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/OrientObjectRepository.java +++ b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/OrientObjectRepository.java @@ -6,11 +6,11 @@ /** * The specific extension for {@link com.orientechnologies.orient.object.db.OObjectDatabaseTx} database. * - * @author Dzmitry_Naskou * @param the generic type to handle + * @author Dzmitry_Naskou */ @NoRepositoryBean public interface OrientObjectRepository extends OrientRepository { - - T detachAll(T entity); + + } diff --git a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/OrientObjectRepositoryFactory.java b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/OrientObjectRepositoryFactory.java index c809a03..00f21d1 100644 --- a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/OrientObjectRepositoryFactory.java +++ b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/OrientObjectRepositoryFactory.java @@ -13,11 +13,12 @@ import org.springframework.data.repository.core.RepositoryInformation; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.RepositoryFactorySupport; +import org.springframework.data.repository.query.EvaluationContextProvider; import org.springframework.data.repository.query.QueryLookupStrategy; import java.io.Serializable; -// TODO: find out why inheriting from OrientRepositoryFactory does not work; would save some code; but this here works +//TODO: find out why inheriting from OrientRepositoryFactory does not work; would save some code; but this here works public class OrientObjectRepositoryFactory extends RepositoryFactorySupport { private final OrientObjectOperations operations; @@ -34,7 +35,7 @@ public EntityInformation getEntityInformatio } @Override - @SuppressWarnings({ "rawtypes", "unchecked"}) + @SuppressWarnings({"rawtypes", "unchecked"}) protected Object getTargetRepository(RepositoryInformation metadata) { EntityInformation entityInformation = getEntityInformation(metadata.getDomainType()); Class repositoryInterface = metadata.getRepositoryInterface(); @@ -57,7 +58,7 @@ protected Object getTargetRepository(RepositoryInformation metadata) { } @Override - protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) { + protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key, EvaluationContextProvider evaluationContextProvider) { return OrientQueryLookupStrategy.create(operations, key); } @@ -70,32 +71,32 @@ protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { } } - private boolean isObjectRepository(Class repositoryInterface) { + private boolean isObjectRepository(Class repositoryInterface) { return OrientObjectRepository.class.isAssignableFrom(repositoryInterface); } /** * Get Custom Cluster Name. * Method looks for {@link org.springframework.data.orient.commons.repository.annotation.Source} and {@link org.springframework.data.orient.commons.repository.annotation.Cluster} annotation. - * + *

* If {@link org.springframework.data.orient.commons.repository.annotation.Source} is not null and {@link org.springframework.data.orient.commons.repository.annotation.Source#type()} equals to * {@link org.springframework.data.orient.commons.repository.SourceType#CLUSTER} then returns {@link org.springframework.data.orient.commons.repository.annotation.Source#value()} - * + *

* If {@link org.springframework.data.orient.commons.repository.annotation.Cluster} is not null then returns {@link org.springframework.data.orient.commons.repository.annotation.Cluster#value()} * * @param metadata * @return cluster name or null if it's not defined */ - private String getCustomCluster(RepositoryMetadata metadata){ + private String getCustomCluster(RepositoryMetadata metadata) { Class repositoryInterface = metadata.getRepositoryInterface(); Source source = AnnotationUtils.getAnnotation(repositoryInterface, Source.class); - if(source != null && SourceType.CLUSTER.equals(source.type())){ + if (source != null && SourceType.CLUSTER.equals(source.type())) { return source.value(); } Cluster cluster = AnnotationUtils.getAnnotation(repositoryInterface, Cluster.class); - if (cluster != null){ + if (cluster != null) { return cluster.value(); } return null; diff --git a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/OrientObjectRepositoryFactoryBean.java b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/OrientObjectRepositoryFactoryBean.java index 32e53af..aa451b4 100644 --- a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/OrientObjectRepositoryFactoryBean.java +++ b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/OrientObjectRepositoryFactoryBean.java @@ -1,7 +1,6 @@ package org.springframework.data.orient.object.repository.support; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.orient.commons.core.OrientOperations; import org.springframework.data.orient.object.OrientObjectOperations; import org.springframework.data.repository.Repository; import org.springframework.data.repository.core.support.RepositoryFactorySupport; @@ -13,18 +12,28 @@ * Special adapter for Springs {@link org.springframework.beans.factory.FactoryBean} interface to allow easy setup of * repository factories via Spring configuration. * - * @author Dzmitry_Naskou - * - * @param the type of the repository - * @param the type of the entity to handle + * @param the type of the repository + * @param the type of the entity to handle * @param the type of the entity identifier to handle + * @author Dzmitry_Naskou */ public class OrientObjectRepositoryFactoryBean, S, ID extends Serializable> extends TransactionalRepositoryFactoryBeanSupport { - /** The orient operations. */ + /** + * The orient operations. + */ @Autowired private OrientObjectOperations operations; + /** + * Creates a new {@link TransactionalRepositoryFactoryBeanSupport} for the given repository interface. + * + * @param repositoryInterface must not be {@literal null}. + */ + protected OrientObjectRepositoryFactoryBean(Class repositoryInterface) { + super(repositoryInterface); + } + @Override protected RepositoryFactorySupport doCreateRepositoryFactory() { return new OrientObjectRepositoryFactory(operations); diff --git a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/SimpleOrientObjectRepository.java b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/SimpleOrientObjectRepository.java index 1141dea..9df173f 100644 --- a/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/SimpleOrientObjectRepository.java +++ b/spring-data-orientdb-object/src/main/java/org/springframework/data/orient/object/repository/support/SimpleOrientObjectRepository.java @@ -31,9 +31,9 @@ public SimpleOrientObjectRepository(OrientObjectOperations operations, Class super(operations, domainClass, cluster, repositoryInterface); } - public T detachAll(T entity) { - // TODO: solve this issue - //return ((OrientObjectOperations) super.operations).detachAll(entity, true); - return entity; - } +// public T detachAll(T entity) { +// // TODO: solve this issue +// //return ((OrientObjectOperations) super.operations).detachAll(entity, true); +// return entity; +// } } diff --git a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientDbObjectTestConfiguration.java b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientDbObjectTestConfiguration.java index 2f3c802..ef03bfa 100644 --- a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientDbObjectTestConfiguration.java +++ b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientDbObjectTestConfiguration.java @@ -19,7 +19,8 @@ @Configuration @EnableTransactionManagement -@EnableOrientRepositories(basePackages = "org.springframework.data.orient.object", repositoryFactoryBeanClass = OrientObjectRepositoryFactoryBean.class) +@EnableOrientRepositories(basePackages = "org.springframework.data.orient.object", + repositoryFactoryBeanClass = OrientObjectRepositoryFactoryBean.class) public class OrientDbObjectTestConfiguration { public static final String EMPLOYEE_TMP_CLUSTER = "employee_tmp"; @@ -33,12 +34,12 @@ public class OrientDbObjectTestConfiguration { @Bean public OrientObjectDatabaseFactory factory() { - OrientObjectDatabaseFactory factory = new OrientObjectDatabaseFactory(); + OrientObjectDatabaseFactory factory = new OrientObjectDatabaseFactory(); - //factory.setUrl("plocal:target/spring-data-orientdb-db"); factory.setUrl("memory:spring-data-orientdb-db"); factory.setUsername("admin"); factory.setPassword("admin"); + factory.setMaxPoolSize(2); return factory; } @@ -71,5 +72,8 @@ public void registerEntities() { int id = db.addCluster(EMPLOYEE_HISTORY_CLUSTER); db.getMetadata().getSchema().getClass(Employee.class).addClusterId(id); } + + db.close(); + } } diff --git a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientObjectDatabaseFactoryTest.java b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientObjectDatabaseFactoryTest.java new file mode 100644 index 0000000..48dd2c6 --- /dev/null +++ b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientObjectDatabaseFactoryTest.java @@ -0,0 +1,50 @@ +package org.springframework.data.orient.object; + +import com.orientechnologies.orient.core.record.impl.ODocument; +import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; +import com.orientechnologies.orient.object.db.OObjectDatabaseTx; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +@Transactional +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {OrientDbObjectTestConfiguration.class}) +public class OrientObjectDatabaseFactoryTest { + + + @Autowired + OrientObjectDatabaseFactory factory; + + @Rule + public TestName name = new TestName(); + + + @Test + public void shouldCountClassElements() throws Exception { + + OObjectDatabaseTx db = factory.db(); + + assertThat(db.countClass("OUser")).isEqualTo(3); + } + + @Test + public void shouldCountClusterElements() throws Exception { + + OObjectDatabaseTx db = factory.db(); + + assertThat(db.countClusterElements("OUser")).isEqualTo(3); + } +} \ No newline at end of file diff --git a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientObjectTemplateTest.java b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientObjectTemplateTest.java new file mode 100644 index 0000000..afc4b33 --- /dev/null +++ b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/OrientObjectTemplateTest.java @@ -0,0 +1,67 @@ +package org.springframework.data.orient.object; + +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; +import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExternalResource; +import org.junit.rules.TestName; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by frank on 12/10/2016. + */ +public class OrientObjectTemplateTest { + + @Rule + public TestName name = new TestName(); + + private OrientObjectTemplate template; + private OrientObjectDatabaseFactory fc; + @Rule + public ExternalResource database = new ExternalResource() { + @Override + protected void before() throws Throwable { + fc = new OrientObjectDatabaseFactory(); + fc.setUrl("memory:" + name.getMethodName()); + fc.setUsername("admin"); + fc.setPassword("admin"); + fc.setMaxPoolSize(2); + //post-construct annotated method for spring + fc.init(); + + template = new OrientObjectTemplate(fc); + + } + + @Override + protected void after() { + + new ODatabaseDocumentTx("memory:" + name.getMethodName()).open("admin", "admin").drop(); + } + }; + + @Test + public void testClassOperations() throws Exception { + + assertThat(template.countClass("OUser")).isEqualTo(3); + + assertThat(template.count(new OSQLSynchQuery<>("Select count(*) from Ouser"))).isEqualTo(3); + + assertThat(template.existsClass("OUser")).isTrue(); + + + } + + @Test + public void testClusterOperations() throws Exception { + + assertThat(template.countClusterElements("OUser")).isEqualTo(3); + + assertThat(template.existsCluster("OUser")).isTrue(); + + } + + +} \ No newline at end of file diff --git a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/context/ContextEnviromentTest.java b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/context/ContextEnviromentTest.java index 8bdc97f..e1acc64 100644 --- a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/context/ContextEnviromentTest.java +++ b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/context/ContextEnviromentTest.java @@ -1,5 +1,7 @@ package org.springframework.data.orient.object.context; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.aop.SpringProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -8,17 +10,16 @@ import org.springframework.data.orient.object.OrientObjectDatabaseFactory; import org.springframework.data.orient.object.OrientObjectOperations; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.testng.annotations.Test; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; -@Configuration @EnableTransactionManagement @ContextConfiguration(classes = OrientDbObjectTestConfiguration.class) -public class ContextEnviromentTest extends AbstractTestNGSpringContextTests{ +@RunWith(SpringJUnit4ClassRunner.class) +public class ContextEnviromentTest { @Autowired ApplicationContext context; diff --git a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/PersonRepository.java b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/PersonRepository.java index e6dced4..de4327a 100644 --- a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/PersonRepository.java +++ b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/PersonRepository.java @@ -10,13 +10,14 @@ import java.util.List; + public interface PersonRepository extends OrientObjectRepository { - @Query("select from person where firstName = ?") + // @Query("select from person where firstName = ?") List findByFirstName(String firstName); - + Page findByFirstName(String firstName, Pageable pageable); - + List findByLastName(String lastName); List findByLastNameLike(String lastName); @@ -26,18 +27,27 @@ public interface PersonRepository extends OrientObjectRepository { List findByFirstNameOrLastName(String firstName, String lastName); List findByFirstNameLike(String string); - + List findByFirstNameStartsWith(String firstName); Long countByFirstName(String firstName); - @Detach(DetachMode.ENTITY) + Long countByActive(Boolean active); + + @Query(value = "select count(*) from person where firstName = ? and active = ?", count = true) + Long countByFirstNameAndActive(String firstName, Boolean active); + + @Detach(DetachMode.ALL) List findByAddress_City(String city); @FetchPlan("*:-1") - List findByAddress_Country(String city); + List findByAddress_Country(String country); List findByActiveIsTrue(); List findByActiveIsFalse(); + + Long deleteByActive(Boolean active); + + } diff --git a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/PersonRepositoryTest.java b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/PersonRepositoryTest.java index b7882ad..0839c2f 100644 --- a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/PersonRepositoryTest.java +++ b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/PersonRepositoryTest.java @@ -1,94 +1,109 @@ package org.springframework.data.orient.object.repository; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.orient.object.OrientDbObjectTestConfiguration; import org.springframework.data.orient.object.OrientObjectDatabaseFactory; import org.springframework.data.orient.object.OrientObjectOperations; import org.springframework.data.orient.object.domain.Address; import org.springframework.data.orient.object.domain.Person; -import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.transaction.TransactionConfiguration; -import org.springframework.transaction.annotation.Transactional; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; -import static org.testng.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; -@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) -@TransactionConfiguration(defaultRollback = true) -@TestExecutionListeners( - inheritListeners = false, - listeners = {DependencyInjectionTestExecutionListener.class}) -@ContextConfiguration(classes = OrientDbObjectTestConfiguration.class) -@Transactional -public class PersonRepositoryTest extends AbstractTestNGSpringContextTests { - private static final Logger logger = LoggerFactory.getLogger(PersonRepositoryTest.class); + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {OrientDbObjectTestConfiguration.class}) +public class PersonRepositoryTest { + + @Autowired + OrientObjectOperations operations; @Autowired PersonRepository repository; - + @Autowired OrientObjectDatabaseFactory factory; - - @Autowired - OrientObjectOperations operations; - - @BeforeClass - public void before() { + + @Before + public void setUp() { + + //cleanup + operations.command("delete from Address"); + operations.command("delete from Person"); + Address esenina = operations.command("insert into Address (country, city, street) values ('Belarus', 'Minsk', 'Esenina')"); - + operations.command("insert into Person (firstName, lastName, active, address) values (?, ?, ?, ?)", "Dzmitry", "Naskou", true, esenina); operations.command("insert into Person (firstName, lastName, active) values ('Koby', 'Eliot', true)"); operations.command("insert into Person (firstName, lastName, active) values ('Ronny', 'Carlisle', true)"); operations.command("insert into Person (firstName, lastName, active) values ('Jameson', 'Matthew', true)"); operations.command("insert into Person (firstName, lastName, active) values ('Roydon', 'Brenden', false)"); } - + + @Test public void repositoryAutowiring() { - assertNotNull(repository); + Assert.assertNotNull(repository); } - + @Test public void savePerson() { Person person = new Person(); person.setFirstName("Jay"); person.setLastName("Miner"); - + String rid = repository.save(person).getRid(); - + Person result = repository.findOne(rid); - + assertEquals(result.getFirstName(), person.getFirstName()); assertEquals(result.getLastName(), person.getLastName()); } @Test public void findAllPersons() { - assertFalse(repository.findAll().isEmpty()); + assertThat(repository.findAll()) + .isNotEmpty() + .hasSize(5); + } @Test public void countPerson() { - assertEquals(repository.count(), 5L); + assertThat(repository.count()).isEqualTo(5L); } @Test public void findByFirstNamePage() { - for (Person person : repository.findByFirstName("Dzmitry", new PageRequest(1, 5)).getContent()) { + + assertThat(repository.findByFirstName("Jameson")).hasSize(1); + Page page = repository.findByFirstName("Jameson", new PageRequest(0, 5)); + + + for (Person person : repository.findByFirstName("Dzmitry", new PageRequest(0, 5)).getContent()) { + System.out.println(person); assertEquals(person.getFirstName(), "Dzmitry"); } } + + @Test + public void findAllPaged() { + + assertThat(repository.findAll(new PageRequest(0, 5)).getContent()).hasSize(5); + } + @Test public void countByFirstName() { assertEquals(repository.countByFirstName("Dzmitry"), Long.valueOf(1)); @@ -112,59 +127,90 @@ public void findByFirstName() { @Test public void findByFirstNameLike() { - for (Person person : repository.findByFirstNameLike("Dzm%")) { - assertTrue(person.getFirstName().startsWith("Dzm")); - } + + assertThat(repository.findByFirstNameLike("Dzm%")) + .hasSize(1) + .first() + .hasFieldOrPropertyWithValue("firstName", "Dzmitry"); } @Test public void findByLastName() { - assertFalse(repository.findByLastName("Naskou").isEmpty()); + assertThat(repository.findByLastName("Naskou")).hasSize(1); } @Test public void findByLastNameLike() { - for (Person person : repository.findByLastNameLike("Na%")) { - assertTrue(person.getLastName().startsWith("Na")); - } + assertThat(repository.findByLastNameLike("Na%")).hasSize(1); } @Test public void findByFirstNameAndLastName() { - for (Person person : repository.findByFirstNameOrLastName("Dzmitry", "Naskou")) { - assertTrue(person.getFirstName().equals("Dzmitry") && person.getLastName().equals("Naskou")); - } + assertThat(repository.findByFirstNameAndLastName("Dzmitry", "Naskou")).hasSize(1); } @Test public void findByFirstNameOrLastName() { - for (Person person : repository.findByFirstNameOrLastName("Dzmitry", "Eliot")) { - assertTrue(person.getFirstName().equals("Dzmitry") || person.getLastName().equals("Eliot")); - } + assertThat(repository.findByFirstNameOrLastName("Dzmitry", "Eliot")).hasSize(2); } @Test public void findByActiveIsTrue() { - for (Person person : repository.findByActiveIsTrue()) { - assertTrue(person.getActive()); - } + assertThat(repository.findByActiveIsTrue()).hasSize(4); } @Test public void findByActiveIsFalse() { - for (Person person : repository.findByActiveIsFalse()) { - assertFalse(person.getActive()); - } + assertThat(repository.findByActiveIsFalse()).hasSize(1); } @Test public void findByCityTest() { - List persons = repository.findByAddress_City("Minsk"); - assertFalse(persons.isEmpty()); + assertThat(repository.findByAddress_City("Minsk")) + .isNotEmpty() + .hasSize(1) + .first() + .extracting("address") + .extracting("city") + .hasSize(1) + .contains("Minsk"); + } - for (Person person : persons) { - assertEquals(person.getAddress().getCity(), "Minsk"); - } + @Test + public void findByCountryTest() { + + assertThat(repository.findByAddress_Country("Belarus")) + .isNotEmpty() + .hasSize(1) + .first() + .extracting("address") + .extracting("country") + .hasSize(1) + .contains("Belarus"); + } + + + @Test + public void deleteByActive() { + assertThat(repository.deleteByActive(false)).isEqualTo(1); + assertThat(repository.deleteByActive(true)).isEqualTo(4); + assertThat(repository.count()).isEqualTo(0); } + + @Test + public void countByActive() { + assertThat(repository.countByActive(false)).isEqualTo(1); + assertThat(repository.countByActive(true)).isEqualTo(4); + } + + @Test + public void countByFirstNameAndActive() { + + assertThat(repository.countByFirstNameAndActive("Dzmitry", true)).isEqualTo(1); + + } + + } + diff --git a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/cluster/EmployeeClusteredRepositoryTest.java b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/cluster/EmployeeClusteredRepositoryTest.java index 9802b38..c9c2a8b 100644 --- a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/cluster/EmployeeClusteredRepositoryTest.java +++ b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/repository/cluster/EmployeeClusteredRepositoryTest.java @@ -3,10 +3,9 @@ import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.object.db.OObjectDatabaseTx; -import java.util.ArrayList; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -16,25 +15,24 @@ import org.springframework.data.orient.object.OrientObjectOperations; import org.springframework.data.orient.object.domain.Employee; import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.transaction.TransactionConfiguration; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.transaction.annotation.Transactional; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.springframework.data.orient.object.OrientDbObjectTestConfiguration.EMPLOYEE_TMP_CLUSTER; -import org.testng.Assert; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) -@TransactionConfiguration(defaultRollback = false) +@Rollback @ContextConfiguration(classes = OrientDbObjectTestConfiguration.class) @Transactional -public class EmployeeClusteredRepositoryTest extends AbstractTestNGSpringContextTests { +public class EmployeeClusteredRepositoryTest extends AbstractJUnit4SpringContextTests { - private static final Logger logger = LoggerFactory.getLogger(EmployeeClusteredRepositoryTest.class); @Autowired OrientObjectDatabaseFactory dbf; @@ -48,8 +46,10 @@ public class EmployeeClusteredRepositoryTest extends AbstractTestNGSpringContext @Autowired OrientObjectOperations operations; - @BeforeClass + @Before public void before() { + operations.command("delete from employee"); + operations.command("insert into cluster:employee (firstName, lastName, active) values ('Dzmitry', 'Naskou', true)"); operations.command("insert into cluster:employee (firstName, lastName, active) values ('Koby', 'Eliot', true)"); operations.command("insert into cluster:employee_tmp (firstName, lastName, active) values ('Ronny', 'Carlisle', true)"); @@ -59,7 +59,8 @@ public void before() { @Test public void findAll() { - logger.debug("Employees: {}", repository.findAll()); + + logger.debug("Employees: " + repository.findAll()); } @Test @@ -89,7 +90,7 @@ public void saveEmployeeToClusterTest() { @Test public void findAllByCluster() { - logger.debug("Employees: {}", repository.findAll(EMPLOYEE_TMP_CLUSTER)); + logger.debug("Employees: " + repository.findAll(EMPLOYEE_TMP_CLUSTER)); } @Test @@ -97,7 +98,7 @@ public void checkClasses() { OObjectDatabaseTx db = dbf.openDatabase(); for (OClass c : db.getMetadata().getSchema().getClasses()) { - logger.debug("Class: {}", c); + logger.debug("Class: " + c); } db.close(); @@ -119,7 +120,7 @@ public void getEmployeeClusters() { OObjectDatabaseTx db = dbf.openDatabase(); for (int i : db.getMetadata().getSchema().getClass(Employee.class).getClusterIds()) { - logger.debug("Cluster ID: {}", i); + logger.debug("Cluster ID: " + i); } db.close(); @@ -158,7 +159,7 @@ public void findByIds() { @Test public void findByLastNameTest() { - logger.debug("Employee: {}", repository.findByLastName("Naskou")); + logger.debug("Employee: " + repository.findByLastName("Naskou")); } @Test diff --git a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/util/OrientOperationUtilTest.java b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/util/OrientOperationUtilTest.java index cfb3c37..43d8dad 100644 --- a/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/util/OrientOperationUtilTest.java +++ b/spring-data-orientdb-object/src/test/java/org/springframework/data/orient/object/util/OrientOperationUtilTest.java @@ -1,34 +1,30 @@ package org.springframework.data.orient.object.util; import com.orientechnologies.orient.object.db.OObjectDatabaseTx; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; import org.springframework.data.orient.object.OrientDbObjectTestConfiguration; import org.springframework.data.orient.object.OrientObjectDatabaseFactory; import org.springframework.data.orient.object.OrientObjectOperations; import org.springframework.data.orient.object.domain.Address; import org.springframework.data.orient.object.domain.Employee; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.transaction.TransactionConfiguration; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -@Configuration -@EnableTransactionManagement -@TransactionConfiguration @ContextConfiguration(classes = OrientDbObjectTestConfiguration.class) -public class OrientOperationUtilTest extends AbstractTestNGSpringContextTests { +@RunWith(SpringJUnit4ClassRunner.class) +public class OrientOperationUtilTest { @Autowired OrientObjectOperations template; @Autowired OrientObjectDatabaseFactory factory; - - @BeforeClass + + @Before public void before() { try (OObjectDatabaseTx db = factory.openDatabase()) { db.getEntityManager().registerEntityClass(Employee.class); @@ -36,7 +32,7 @@ public void before() { } @Test - public void getRidTest(){ + public void getRidTest() { Address address = new Address(); Assert.assertNull(template.getRid(address)); @@ -45,7 +41,7 @@ public void getRidTest(){ } @Test - public void getRidFromParentTest(){ + public void getRidFromParentTest() { Employee employee = new Employee(); Assert.assertNull(template.getRid(employee)); @@ -54,10 +50,10 @@ public void getRidFromParentTest(){ } @Test - public void getRidFromProxy(){ + public void getRidFromProxy() { Employee employee = new Employee(); Employee savedEmployee = template.save(employee); - + Assert.assertNotSame(savedEmployee.getClass(), Employee.class); Assert.assertEquals(template.getRid(savedEmployee), savedEmployee.getRid()); } diff --git a/spring-data-orientdb-object/src/test/resources/logback.xml b/spring-data-orientdb-object/src/test/resources/logback.xml index 41a4d21..089835d 100644 --- a/spring-data-orientdb-object/src/test/resources/logback.xml +++ b/spring-data-orientdb-object/src/test/resources/logback.xml @@ -2,7 +2,7 @@ true - %green(%d{HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %cyan(%logger{36}) - %msg%n + %green(%d{HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %cyan(%logger{36})[%line] - %msg%n @@ -17,13 +17,13 @@ - + - + diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-hello/pom.xml b/spring-data-orientdb-samples/spring-boot-orientdb-hello/pom.xml index 1513211..bffe30d 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-hello/pom.xml +++ b/spring-data-orientdb-samples/spring-boot-orientdb-hello/pom.xml @@ -1,17 +1,15 @@ - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT ../../pom.xml - org.springframework.boot.samples + com.orientechnologies.samples spring-boot-orientdb-hello jar Sample - Spring Boot OrientDB Hello @@ -20,7 +18,7 @@ - org.springframework.boot + com.orientechnologies spring-boot-orientdb-autoconfigure ${project.version} @@ -35,6 +33,11 @@ spring-boot-starter-test test + + com.orientechnologies + spring-data-orientdb-object + ${project.version} + diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/HelloApplication.java b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/HelloApplication.java index f1c5fc5..63d59f0 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/HelloApplication.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/HelloApplication.java @@ -23,69 +23,69 @@ @EnableOrientRepositories("org.springframework.boot.orientdb.hello.repository") public class HelloApplication implements CommandLineRunner { - @Autowired - private PersonRepository repository; + @Autowired + private PersonRepository repository; - @Autowired - private OrientObjectDatabaseFactory factory; + @Autowired + private OrientObjectDatabaseFactory factory; - public static void main(String[] args) { - SpringApplication.run(HelloApplication.class, args); + public static void main(String[] args) { + SpringApplication.run(HelloApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + OObjectDatabaseTx db = null; + + try { + db = factory.openDatabase(); + db.getEntityManager().registerEntityClass(Person.class); + } finally { + if (db != null) { + db.close(); + } } - @Override - public void run(String... args) throws Exception { - OObjectDatabaseTx db = null; - - try { - db = factory.openDatabase(); - db.getEntityManager().registerEntityClass(Person.class); - } finally { - if (db != null) { - db.close(); - } - } - - //Create Persons if required - if (repository.count() < 1) { - List persons = new ArrayList(); - - Person graham = new Person(); - graham.setFirstName("Graham"); - graham.setLastName("Jacobson"); - graham.setAge(25); - - persons.add(graham); - - Person ebony = new Person(); - ebony.setFirstName("Ebony"); - ebony.setLastName("Irwin"); - ebony.setAge(21); - - persons.add(ebony); - - Person benedict = new Person(); - benedict.setFirstName("Benedict"); - benedict.setLastName("Preston"); - benedict.setAge(25); - - persons.add(benedict); - - Person zorita = new Person(); - zorita.setFirstName("Zorita"); - zorita.setLastName("Clements"); - zorita.setAge(23); - - persons.add(zorita); - - Person kaitlin = new Person(); - kaitlin.setFirstName("Kaitlin"); - kaitlin.setLastName("Walter"); - kaitlin.setAge(22); - - persons.add(kaitlin); - - repository.save(persons); - } + //Create Persons if required + if (repository.count() < 1) { + List persons = new ArrayList(); + + Person graham = new Person(); + graham.setFirstName("Graham"); + graham.setLastName("Jacobson"); + graham.setAge(25); + + persons.add(graham); + + Person ebony = new Person(); + ebony.setFirstName("Ebony"); + ebony.setLastName("Irwin"); + ebony.setAge(21); + + persons.add(ebony); + + Person benedict = new Person(); + benedict.setFirstName("Benedict"); + benedict.setLastName("Preston"); + benedict.setAge(25); + + persons.add(benedict); + + Person zorita = new Person(); + zorita.setFirstName("Zorita"); + zorita.setLastName("Clements"); + zorita.setAge(23); + + persons.add(zorita); + + Person kaitlin = new Person(); + kaitlin.setFirstName("Kaitlin"); + kaitlin.setLastName("Walter"); + kaitlin.setAge(22); + + persons.add(kaitlin); + + repository.save(persons); } + } } diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/HelloConfiguration.java b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/HelloConfiguration.java index 17ed8d3..b5dfef3 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/HelloConfiguration.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/HelloConfiguration.java @@ -1,44 +1,45 @@ package org.springframework.boot.orientdb.hello; -import javax.annotation.PostConstruct; +import org.springframework.boot.orientdb.hello.data.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.data.orient.commons.core.OrientTransactionManager; import org.springframework.data.orient.commons.repository.config.EnableOrientRepositories; import org.springframework.data.orient.object.OrientObjectDatabaseFactory; -import org.springframework.data.orient.commons.core.OrientTransactionManager; import org.springframework.data.orient.object.OrientObjectTemplate; -import org.springframework.boot.orientdb.hello.data.Person; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.annotation.PostConstruct; @Configuration @EnableTransactionManagement @EnableOrientRepositories(basePackages = "org.springframework.boot.orientdb.hello.data") public class HelloConfiguration { - @Bean - public OrientObjectDatabaseFactory factory() { - OrientObjectDatabaseFactory factory = new OrientObjectDatabaseFactory(); - - factory.setUrl("remote:127.0.0.1/GratefulDeadConcerts"); - factory.setUsername("admin"); - factory.setPassword("admin"); + @Bean + public OrientObjectDatabaseFactory factory() { + OrientObjectDatabaseFactory factory = new OrientObjectDatabaseFactory(); - return factory; - } + factory.setUrl("memory:helloDb"); + factory.setUsername("admin"); + factory.setPassword("admin"); + factory.setMaxPoolSize(10); - @Bean - public OrientTransactionManager transactionManager() { - return new OrientTransactionManager(factory()); - } + return factory; + } - @Bean - public OrientObjectTemplate objectTemplate() { - return new OrientObjectTemplate(factory()); - } + @Bean + public OrientTransactionManager transactionManager() { + return new OrientTransactionManager(factory()); + } + @Bean + public OrientObjectTemplate objectTemplate() { + return new OrientObjectTemplate(factory()); + } - @PostConstruct - public void registerEntities() { - factory().db().getEntityManager().registerEntityClass(Person.class); - } + @PostConstruct + public void registerEntities() { + factory().db().getEntityManager().registerEntityClass(Person.class); + } } diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/data/Person.java b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/data/Person.java index a061654..eb2a66d 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/data/Person.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/data/Person.java @@ -2,60 +2,55 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import javax.persistence.Id; import javax.persistence.Version; -@JsonIgnoreProperties(value = {"handler"}) +@JsonIgnoreProperties(value = { "handler" }) public class Person { - @Id - private String id; - - @Version - @JsonIgnore - private Long version; - - /** - * Added to avoid a runtime error whereby the detachAll property is checked - * for existence but not actually used. - */ - private String detachAll; - - private String firstName; - - private String lastName; - - private Integer age; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } + @Id + private String id; + + @Version + @JsonIgnore + private Long version; + + private String firstName; + + private String lastName; + + private Integer age; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } } diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/repository/PersonRepository.java b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/repository/PersonRepository.java index 3797053..ceb95c1 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/repository/PersonRepository.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/repository/PersonRepository.java @@ -1,17 +1,25 @@ package org.springframework.boot.orientdb.hello.repository; import org.springframework.boot.orientdb.hello.data.Person; +import org.springframework.data.orient.commons.repository.DetachMode; +import org.springframework.data.orient.commons.repository.annotation.Detach; import org.springframework.data.orient.commons.repository.annotation.Query; import org.springframework.data.orient.object.repository.OrientObjectRepository; import java.util.List; public interface PersonRepository extends OrientObjectRepository { - - List findByFirstName(String firstName); - - @Query("select from person where lastName = ?") - List findByLastName(String lastName); - - List findByAge(Integer age); + + @Override + @Detach(DetachMode.ALL) + List findAll(); + + List findByFirstName(String firstName); + + @Query("select from person where lastName = ?") + List findByLastName(String lastName); + + List findByAge(Integer age); + + Long deleteByAge(Integer age); } diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/rest/PersonController.java b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/rest/PersonController.java index d2c39f8..299cb6c 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/rest/PersonController.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-hello/src/main/java/org/springframework/boot/orientdb/hello/rest/PersonController.java @@ -14,26 +14,31 @@ @RequestMapping("/persons") public class PersonController { - @Autowired - private PersonRepository repository; - - @RequestMapping(method = RequestMethod.GET) - public List findAllPersons() { - return repository.findAll(); - } - - @RequestMapping("/findByFirstName") - public List findByFirstName(@RequestParam String firstName) { - return repository.findByFirstName(firstName); - } - - @RequestMapping("/findByLastName") - public List findByLastName(@RequestParam String lastName) { - return repository.findByLastName(lastName); - } - - @RequestMapping("/findByAge") - public List findByAge(@RequestParam Integer age) { - return repository.findByAge(age); - } + @Autowired + private PersonRepository repository; + + @RequestMapping(method = RequestMethod.GET) + public List findAllPersons() { + return repository.findAll(); + } + + @RequestMapping("/findByFirstName") + public List findByFirstName(@RequestParam String firstName) { + return repository.findByFirstName(firstName); + } + + @RequestMapping("/findByLastName") + public List findByLastName(@RequestParam String lastName) { + return repository.findByLastName(lastName); + } + + @RequestMapping("/findByAge") + public List findByAge(@RequestParam Integer age) { + return repository.findByAge(age); + } + + @RequestMapping("/deleteByAge") + public Long deleteByAge(@RequestParam Integer age) { + return repository.deleteByAge(age); + } } diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/pom.xml b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/pom.xml index 33a2870..4005dbe 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/pom.xml +++ b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/pom.xml @@ -1,17 +1,15 @@ - + 4.0.0 - org.springframework.data + com.orientechnologies spring-data-orientdb-parent - 0.10.0-SNAPSHOT + 0.15-SNAPSHOT ../../pom.xml - org.springframework.boot.samples + com.orientechnologies.samples spring-boot-orientdb-shiro jar Sample - Spring Boot OrientDB Shiro @@ -32,9 +30,9 @@ - org.springframework.boot + com.orientechnologies spring-boot-orientdb-autoconfigure - ${project.version} + ${project.parent.version} org.springframework.boot @@ -73,6 +71,20 @@ spring-boot-starter-test test + + org.springframework + spring-tx + + + com.orientechnologies + spring-data-orientdb-commons + ${project.version} + + + com.orientechnologies + spring-data-orientdb-object + ${project.version} + @@ -114,6 +126,13 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + true + + diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/Application.java b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/Application.java index 0819541..7886747 100755 --- a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/Application.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/Application.java @@ -2,8 +2,8 @@ * 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 - * + * 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 @@ -12,18 +12,23 @@ */ package org.springframework.boot.orient.sample.shiro; +import org.springframework.boot.Banner; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan -public class Application { +public final class Application { + + private Application() throws InstantiationException { + throw new InstantiationException("This class is not for instantiation"); + } public static void main(String... args) { new SpringApplicationBuilder() .sources(Application.class) - .showBanner(false) + .bannerMode(Banner.Mode.OFF) .run(args); } diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/OrientDbConfiguration.java b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/OrientDbConfiguration.java index 24eae92..6afd853 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/OrientDbConfiguration.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/OrientDbConfiguration.java @@ -2,8 +2,8 @@ * 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 - * + * 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 @@ -13,24 +13,67 @@ package org.springframework.boot.orient.sample.shiro; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; +import org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory; +import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.data.orient.commons.core.OrientTransactionManager; import org.springframework.data.orient.commons.repository.config.EnableOrientRepositories; import org.springframework.data.orient.object.OrientObjectDatabaseFactory; +import org.springframework.data.orient.object.OrientObjectOperations; +import org.springframework.data.orient.object.OrientObjectTemplate; import org.springframework.data.orient.object.repository.support.OrientObjectRepositoryFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; @Configuration -@EnableOrientRepositories(basePackages = "org.springframework.boot.orient.sample.shiro.repository", repositoryFactoryBeanClass = OrientObjectRepositoryFactoryBean.class) +@EnableTransactionManagement +@EnableOrientRepositories(basePackages = "org.springframework.boot.orient.sample.shiro.repository", + repositoryFactoryBeanClass = OrientObjectRepositoryFactoryBean.class) public class OrientDbConfiguration { - @Autowired - private OrientObjectDatabaseFactory factory; +// @Autowired +// private OrientObjectDatabaseFactory factory; + + + @Bean + public OrientObjectDatabaseFactory factory() { + OrientObjectDatabaseFactory factory = new OrientObjectDatabaseFactory(); + factory.setUrl("memory:spring-data-orientdb-db"); + factory.setUsername("admin"); + factory.setPassword("admin"); + + return factory; + } @PostConstruct @Transactional public void registerEntities() { - factory.db().getEntityManager().registerEntityClasses("org.springframework.boot.orient.sample.shiro.model"); + factory().db().getEntityManager().registerEntityClasses("org.springframework.boot.orient.sample.shiro.model"); + + + } + + @Bean + public OrientTransactionManager transactionManager() { + return new OrientTransactionManager(factory()); } + + + @Bean + public OrientObjectOperations objectTemplate() { + return new OrientObjectTemplate(factory()); + } + + + @Bean + public EmbeddedServletContainerFactory servletContainer() { + TomcatEmbeddedServletContainerFactory factory = + new TomcatEmbeddedServletContainerFactory(); + return factory; + } + } diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/shiro/HazelcastSessionDao.java b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/shiro/HazelcastSessionDao.java index 45162c7..6d95d4a 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/shiro/HazelcastSessionDao.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/main/java/org/springframework/boot/orient/sample/shiro/shiro/HazelcastSessionDao.java @@ -34,8 +34,8 @@ public class HazelcastSessionDao extends AbstractSessionDAO { private static final Logger log = LoggerFactory .getLogger(HazelcastSessionDao.class); - private String hcInstanceName = UUID.randomUUID().toString(); - private IMap map; + private final String hcInstanceName = UUID.randomUUID().toString(); + private final IMap map; private static final String HC_MAP = "sessions"; private static final String HC_GROUP_NAME = "hc"; private static final String HC_GROUP_PASSWORD = "oursessionssecret"; diff --git a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/test/java/org/springframework/boot/orient/sample/shiro/rest/UserControllerTest.java b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/test/java/org/springframework/boot/orient/sample/shiro/rest/UserControllerTest.java index de88316..f9e572e 100644 --- a/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/test/java/org/springframework/boot/orient/sample/shiro/rest/UserControllerTest.java +++ b/spring-data-orientdb-samples/spring-boot-orientdb-shiro/src/test/java/org/springframework/boot/orient/sample/shiro/rest/UserControllerTest.java @@ -2,8 +2,8 @@ * 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 - * + * 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 @@ -16,6 +16,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.DefaultPasswordService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.orient.sample.shiro.Application; import org.springframework.boot.orient.sample.shiro.OrientDbConfiguration; @@ -26,30 +29,25 @@ import org.springframework.boot.orient.sample.shiro.repository.PermissionRepository; import org.springframework.boot.orient.sample.shiro.repository.RoleRepository; import org.springframework.boot.orient.sample.shiro.repository.UserRepository; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.boot.test.TestRestTemplate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.*; import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.springframework.test.context.web.WebAppConfiguration; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import java.util.Arrays; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; -import static org.testng.AssertJUnit.assertEquals; +import static org.junit.Assert.assertEquals; -@SpringApplicationConfiguration(classes - = {Application.class, OrientDbConfiguration.class, ShiroConfiguration.class}) +@SpringBootTest(classes = {Application.class, OrientDbConfiguration.class, ShiroConfiguration.class}) @WebAppConfiguration -@IntegrationTest -@TestExecutionListeners(inheritListeners = false, listeners - = {DependencyInjectionTestExecutionListener.class}) -public class UserControllerTest extends AbstractTestNGSpringContextTests { +@TestExecutionListeners(inheritListeners = false, listeners = {DependencyInjectionTestExecutionListener.class}) +@RunWith(SpringJUnit4ClassRunner.class) +public class UserControllerTest { private final String BASE_URL = "http://localhost:8080/users"; private final String USER_NAME = "Paulo Pires"; @@ -64,7 +62,7 @@ public class UserControllerTest extends AbstractTestNGSpringContextTests { @Autowired private PermissionRepository permissionRepo; - @BeforeClass + @Before public void setUp() { // clean-up users, roles and permissions userRepo.deleteAll();