From 6ab6050690fa07b6306e42c540521560ee09018f Mon Sep 17 00:00:00 2001 From: Christoph Strobl Date: Mon, 13 Feb 2017 15:01:50 +0100 Subject: [PATCH] DATAJPA-1064 - Integrate Data Commons Java 8 upgrade branch. Make sure things compile again and do the same as they have done before by checking and fixing unit and integration tests. --- .../data/jpa/domain/AbstractAuditable.java | 42 +++++++++-------- .../support/AuditingEntityListener.java | 9 ++-- .../mapping/JpaMetamodelMappingContext.java | 8 ++-- .../jpa/mapping/JpaPersistentEntityImpl.java | 16 ++++--- .../mapping/JpaPersistentPropertyImpl.java | 45 ++++++++++-------- .../jpa/repository/cdi/JpaRepositoryBean.java | 8 ++-- .../cdi/JpaRepositoryExtension.java | 6 ++- .../config/JpaRepositoryConfigExtension.java | 22 +++++---- .../repository/query/AbstractJpaQuery.java | 4 +- .../repository/query/JpaQueryExecution.java | 26 +++++------ .../jpa/repository/query/JpaQueryMethod.java | 4 +- .../jpa/repository/query/ParameterBinder.java | 12 +++-- .../query/ParameterMetadataProvider.java | 3 +- .../repository/query/PartTreeJpaQuery.java | 6 ++- .../query/StoredProcedureJpaQuery.java | 5 +- .../query/StringQueryParameterBinder.java | 3 +- .../JpaMetamodelEntityInformation.java | 11 ++--- .../JpaPersistableEntityInformation.java | 8 ++-- .../support/JpaRepositoryFactory.java | 15 +++--- .../data/jpa/repository/support/Querydsl.java | 4 +- ...sitory.java => QuerydslJpaRepository.java} | 30 +++++------- .../support/SimpleJpaRepository.java | 38 +++++++-------- .../data/jpa/domain/sample/AuditableUser.java | 3 +- .../jpa/domain/sample/AuditorAwareStub.java | 6 ++- .../support/AuditingEntityListenerTests.java | 18 +++++--- ...tamodelMappingContextIntegrationTests.java | 25 +++++----- .../JpaPersistentPropertyImplUnitTests.java | 15 +++--- .../PersistenceProviderIntegrationTests.java | 2 +- .../AbstractPersistableIntegrationTests.java | 2 +- ...omAbstractPersistableIntegrationTests.java | 2 +- ...raphRepositoryMethodsIntegrationTests.java | 2 +- .../RepositoryWithCompositeKeyTests.java | 8 ++-- .../RepositoryWithIdClassKeyTests.java | 5 +- .../RoleRepositoryIntegrationTests.java | 4 +- .../jpa/repository/UserRepositoryTests.java | 16 +++---- ...uditingViaJavaConfigRepositoriesTests.java | 21 ++++++--- .../custom/UserCustomExtendedRepository.java | 3 +- .../query/JpaQueryMethodUnitTests.java | 3 +- .../query/ParameterBinderUnitTests.java | 4 +- .../EmployeeRepositoryWithEmbeddedId.java | 4 +- .../sample/EmployeeRepositoryWithIdClass.java | 4 +- .../sample/MailMessageRepository.java | 4 +- ...ethodsWithEntityGraphConfigRepository.java | 7 +-- .../jpa/repository/sample/RoleRepository.java | 8 ++-- .../jpa/repository/sample/UserRepository.java | 2 +- .../JpaEntityInformationSupportUnitTests.java | 5 +- ...odelEntityInformationIntegrationTests.java | 13 ++---- ...paMetamodelEntityInformationUnitTests.java | 3 +- ...PersistableEntityInformationUnitTests.java | 6 ++- .../JpaRepositoryFactoryBeanUnitTests.java | 46 +++++++++++++++++-- .../JpaRepositoryFactoryUnitTests.java | 11 +++-- .../support/JpaRepositoryTests.java | 5 +- .../support/QueryDslJpaRepositoryTests.java | 6 +-- .../namespace-customfactory-context.xml | 3 +- 54 files changed, 342 insertions(+), 249 deletions(-) rename src/main/java/org/springframework/data/jpa/repository/support/{QueryDslJpaRepository.java => QuerydslJpaRepository.java} (89%) diff --git a/src/main/java/org/springframework/data/jpa/domain/AbstractAuditable.java b/src/main/java/org/springframework/data/jpa/domain/AbstractAuditable.java index 767b67958..4ee286233 100644 --- a/src/main/java/org/springframework/data/jpa/domain/AbstractAuditable.java +++ b/src/main/java/org/springframework/data/jpa/domain/AbstractAuditable.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2011 the original author or authors. + * Copyright 2008-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,29 @@ package org.springframework.data.jpa.domain; import java.io.Serializable; +import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.Date; +import java.util.Optional; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.joda.time.DateTime; import org.springframework.data.domain.Auditable; /** * Abstract base class for auditable entities. Stores the audition values in persistent fields. * * @author Oliver Gierke + * @author Christoph Strobl * @param the auditing type. Typically some kind of user. * @param the type of the auditing type's idenifier */ @MappedSuperclass public abstract class AbstractAuditable extends AbstractPersistable implements - Auditable { + Auditable { private static final long serialVersionUID = 141481953116476081L; @@ -56,9 +59,9 @@ public abstract class AbstractAuditable extends Abst * * @see org.springframework.data.domain.Auditable#getCreatedBy() */ - public U getCreatedBy() { + public Optional getCreatedBy() { - return createdBy; + return Optional.ofNullable(createdBy); } /* @@ -67,9 +70,9 @@ public abstract class AbstractAuditable extends Abst * @see * org.springframework.data.domain.Auditable#setCreatedBy(java.lang.Object) */ - public void setCreatedBy(final U createdBy) { + public void setCreatedBy(final Optional createdBy) { - this.createdBy = createdBy; + this.createdBy = createdBy.orElse(null); } /* @@ -77,9 +80,10 @@ public abstract class AbstractAuditable extends Abst * * @see org.springframework.data.domain.Auditable#getCreatedDate() */ - public DateTime getCreatedDate() { + @Override + public Optional getCreatedDate() { - return null == createdDate ? null : new DateTime(createdDate); + return null == createdDate ? Optional.empty() : Optional.of(LocalDateTime.ofInstant(createdDate.toInstant(), ZoneId.systemDefault())); } /* @@ -89,9 +93,9 @@ public abstract class AbstractAuditable extends Abst * org.springframework.data.domain.Auditable#setCreatedDate(org.joda.time * .DateTime) */ - public void setCreatedDate(final DateTime createdDate) { + public void setCreatedDate(Optional createdDate) { - this.createdDate = null == createdDate ? null : createdDate.toDate(); + this.createdDate = createdDate.map(d -> Date.from(d.atZone(ZoneId.systemDefault()).toInstant())).orElse(null); } /* @@ -99,9 +103,9 @@ public abstract class AbstractAuditable extends Abst * * @see org.springframework.data.domain.Auditable#getLastModifiedBy() */ - public U getLastModifiedBy() { + public Optional getLastModifiedBy() { - return lastModifiedBy; + return Optional.ofNullable(lastModifiedBy); } /* @@ -111,9 +115,9 @@ public abstract class AbstractAuditable extends Abst * org.springframework.data.domain.Auditable#setLastModifiedBy(java.lang * .Object) */ - public void setLastModifiedBy(final U lastModifiedBy) { + public void setLastModifiedBy(final Optional lastModifiedBy) { - this.lastModifiedBy = lastModifiedBy; + this.lastModifiedBy = lastModifiedBy.orElse(null); } /* @@ -121,9 +125,9 @@ public abstract class AbstractAuditable extends Abst * * @see org.springframework.data.domain.Auditable#getLastModifiedDate() */ - public DateTime getLastModifiedDate() { + public Optional getLastModifiedDate() { - return null == lastModifiedDate ? null : new DateTime(lastModifiedDate); + return null == lastModifiedDate ? Optional.empty() : Optional.of(LocalDateTime.ofInstant(lastModifiedDate.toInstant(), ZoneId.systemDefault())); } /* @@ -133,8 +137,8 @@ public abstract class AbstractAuditable extends Abst * org.springframework.data.domain.Auditable#setLastModifiedDate(org.joda * .time.DateTime) */ - public void setLastModifiedDate(final DateTime lastModifiedDate) { + public void setLastModifiedDate(Optional lastModifiedDate) { - this.lastModifiedDate = null == lastModifiedDate ? null : lastModifiedDate.toDate(); + this.lastModifiedDate = lastModifiedDate.map(d -> Date.from(d.atZone(ZoneId.systemDefault()).toInstant())).orElse(null); } } diff --git a/src/main/java/org/springframework/data/jpa/domain/support/AuditingEntityListener.java b/src/main/java/org/springframework/data/jpa/domain/support/AuditingEntityListener.java index b202eae05..42f0131c5 100644 --- a/src/main/java/org/springframework/data/jpa/domain/support/AuditingEntityListener.java +++ b/src/main/java/org/springframework/data/jpa/domain/support/AuditingEntityListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,8 @@ package org.springframework.data.jpa.domain.support; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; +import java.util.Optional; + import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.data.auditing.AuditingHandler; @@ -54,6 +56,7 @@ import org.springframework.util.Assert; * * @author Oliver Gierke * @author Thomas Darimont + * @author Christoph Strobl */ @Configurable public class AuditingEntityListener { @@ -80,7 +83,7 @@ public class AuditingEntityListener { @PrePersist public void touchForCreate(Object target) { if (handler != null) { - handler.getObject().markCreated(target); + handler.getObject().markCreated(Optional.ofNullable(target)); } } @@ -93,7 +96,7 @@ public class AuditingEntityListener { @PreUpdate public void touchForUpdate(Object target) { if (handler != null) { - handler.getObject().markModified(target); + handler.getObject().markModified(Optional.ofNullable(target)); } } } diff --git a/src/main/java/org/springframework/data/jpa/mapping/JpaMetamodelMappingContext.java b/src/main/java/org/springframework/data/jpa/mapping/JpaMetamodelMappingContext.java index 13172aafe..babbd9531 100644 --- a/src/main/java/org/springframework/data/jpa/mapping/JpaMetamodelMappingContext.java +++ b/src/main/java/org/springframework/data/jpa/mapping/JpaMetamodelMappingContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import javax.persistence.metamodel.Metamodel; import org.springframework.data.jpa.provider.PersistenceProvider; import org.springframework.data.mapping.context.AbstractMappingContext; import org.springframework.data.mapping.context.MappingContext; +import org.springframework.data.mapping.model.Property; import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.util.TypeInformation; import org.springframework.util.Assert; @@ -33,6 +34,7 @@ import org.springframework.util.Assert; * {@link MappingContext} implementation based on a Jpa {@link Metamodel}. * * @author Oliver Gierke + * @author Christoph Strobl * @since 1.3 */ public class JpaMetamodelMappingContext @@ -69,11 +71,11 @@ public class JpaMetamodelMappingContext * @see org.springframework.data.mapping.context.AbstractMappingContext#createPersistentProperty(java.lang.reflect.Field, java.beans.PropertyDescriptor, org.springframework.data.mapping.model.MutablePersistentEntity, org.springframework.data.mapping.model.SimpleTypeHolder) */ @Override - protected JpaPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, + protected JpaPersistentProperty createPersistentProperty(Property property, JpaPersistentEntityImpl owner, SimpleTypeHolder simpleTypeHolder) { Metamodel metamodel = getMetamodelFor(owner.getType()); - return new JpaPersistentPropertyImpl(metamodel, field, descriptor, owner, simpleTypeHolder); + return new JpaPersistentPropertyImpl(metamodel, property, owner, simpleTypeHolder); } /* diff --git a/src/main/java/org/springframework/data/jpa/mapping/JpaPersistentEntityImpl.java b/src/main/java/org/springframework/data/jpa/mapping/JpaPersistentEntityImpl.java index 4b1252723..9da1434cf 100644 --- a/src/main/java/org/springframework/data/jpa/mapping/JpaPersistentEntityImpl.java +++ b/src/main/java/org/springframework/data/jpa/mapping/JpaPersistentEntityImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package org.springframework.data.jpa.mapping; import java.util.Comparator; +import java.util.Optional; import org.springframework.data.annotation.Version; import org.springframework.data.jpa.provider.ProxyIdAccessor; @@ -30,6 +31,7 @@ import org.springframework.util.Assert; * * @author Oliver Gierke * @author Greg Turnquist + * @author Christoph Strobl * @since 1.3 */ class JpaPersistentEntityImpl extends BasicPersistentEntity @@ -49,7 +51,7 @@ class JpaPersistentEntityImpl extends BasicPersistentEntity information, ProxyIdAccessor proxyIdAccessor) { - super(information, null); + super(information, Optional.empty()); Assert.notNull(proxyIdAccessor, "ProxyIdAccessor must not be null!"); this.proxyIdAccessor = proxyIdAccessor; @@ -82,13 +84,13 @@ class JpaPersistentEntityImpl extends BasicPersistentEntity versionProperty = getVersionProperty(); - if (versionProperty == null) { + if (!versionProperty.isPresent()) { return; } - if (versionProperty.isAnnotationPresent(Version.class)) { + if (versionProperty.get().isAnnotationPresent(Version.class)) { throw new IllegalArgumentException(String.format(INVALID_VERSION_ANNOTATION, versionProperty)); } } @@ -129,8 +131,8 @@ class JpaPersistentEntityImpl extends BasicPersistentEntity getIdentifier() { + return proxyIdAccessor.shouldUseAccessorFor(bean) ? Optional.ofNullable(proxyIdAccessor.getIdentifierFrom(bean)) : super.getIdentifier(); } } diff --git a/src/main/java/org/springframework/data/jpa/mapping/JpaPersistentPropertyImpl.java b/src/main/java/org/springframework/data/jpa/mapping/JpaPersistentPropertyImpl.java index 55eb5fde7..7213f1f08 100644 --- a/src/main/java/org/springframework/data/jpa/mapping/JpaPersistentPropertyImpl.java +++ b/src/main/java/org/springframework/data/jpa/mapping/JpaPersistentPropertyImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.lang.reflect.Field; import java.util.Collection; import java.util.Collections; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import javax.persistence.Access; @@ -45,6 +46,7 @@ import org.springframework.data.jpa.util.JpaMetamodel; import org.springframework.data.mapping.Association; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty; +import org.springframework.data.mapping.model.Property; import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; @@ -55,6 +57,7 @@ import org.springframework.util.Assert; * * @author Oliver Gierke * @author Greg Turnquist + * @author Christoph Strobl * @since 1.3 */ class JpaPersistentPropertyImpl extends AnnotationBasedPersistentProperty @@ -97,15 +100,14 @@ class JpaPersistentPropertyImpl extends AnnotationBasedPersistentProperty owner, SimpleTypeHolder simpleTypeHolder) { - super(field, propertyDescriptor, owner, simpleTypeHolder); + super(property, owner, simpleTypeHolder); Assert.notNull(metamodel, "Metamodel must not be null!"); @@ -234,27 +236,27 @@ class JpaPersistentPropertyImpl extends AnnotationBasedPersistentProperty accessType = findAnnotation( org.springframework.data.annotation.AccessType.class); - if (accessType != null) { - return Type.PROPERTY.equals(accessType.value()); + if (accessType.isPresent()) { + return Type.PROPERTY.equals(accessType.get().value()); } - Access access = findAnnotation(Access.class); + Optional access = findAnnotation(Access.class); - if (access != null) { - return AccessType.PROPERTY.equals(access.value()); + if (access.isPresent()) { + return AccessType.PROPERTY.equals(access.get().value()); } accessType = findPropertyOrOwnerAnnotation(org.springframework.data.annotation.AccessType.class); - if (accessType != null) { - return Type.PROPERTY.equals(accessType.value()); + if (accessType.isPresent()) { + return Type.PROPERTY.equals(accessType.get().value()); } access = findPropertyOrOwnerAnnotation(Access.class); - return access == null ? null : AccessType.PROPERTY.equals(access.value()); + return access.map(t -> AccessType.PROPERTY.equals(t.value())).orElse(null); } /** @@ -266,11 +268,14 @@ class JpaPersistentPropertyImpl extends AnnotationBasedPersistentProperty associationAnnotation : ASSOCIATION_ANNOTATIONS) { - Annotation annotation = findAnnotation(associationAnnotation); - Object targetEntity = AnnotationUtils.getValue(annotation, "targetEntity"); + Optional annotation = findAnnotation(associationAnnotation); + if(annotation.isPresent()) { - if (targetEntity != null && !void.class.equals(targetEntity)) { - return ClassTypeInformation.from((Class) targetEntity); + Object targetEntity = AnnotationUtils.getValue(annotation.get(), "targetEntity"); + + if (targetEntity != null && !void.class.equals(targetEntity)) { + return ClassTypeInformation.from((Class) targetEntity); + } } } @@ -287,9 +292,9 @@ class JpaPersistentPropertyImpl extends AnnotationBasedPersistentProperty annotationType : UPDATEABLE_ANNOTATIONS) { - Annotation annotation = findAnnotation(annotationType); + Optional annotation = findAnnotation(annotationType); - if (annotation != null && AnnotationUtils.getValue(annotation, "updatable").equals(Boolean.FALSE)) { + if (annotation.isPresent() && AnnotationUtils.getValue(annotation.get(), "updatable").equals(Boolean.FALSE)) { return false; } } diff --git a/src/main/java/org/springframework/data/jpa/repository/cdi/JpaRepositoryBean.java b/src/main/java/org/springframework/data/jpa/repository/cdi/JpaRepositoryBean.java index f4079977f..e86107411 100644 --- a/src/main/java/org/springframework/data/jpa/repository/cdi/JpaRepositoryBean.java +++ b/src/main/java/org/springframework/data/jpa/repository/cdi/JpaRepositoryBean.java @@ -16,6 +16,7 @@ package org.springframework.data.jpa.repository.cdi; import java.lang.annotation.Annotation; +import java.util.Optional; import java.util.Set; import javax.enterprise.context.spi.CreationalContext; @@ -34,6 +35,7 @@ import org.springframework.util.Assert; * @author Dirk Mahler * @author Oliver Gierke * @author Mark Paluch + * @author Christoph Strobl * @param The type of the repository. */ class JpaRepositoryBean extends CdiRepositoryBean { @@ -50,7 +52,7 @@ class JpaRepositoryBean extends CdiRepositoryBean { * @param detector can be {@literal null}. */ JpaRepositoryBean(BeanManager beanManager, Bean entityManagerBean, Set qualifiers, - Class repositoryType, CustomRepositoryImplementationDetector detector) { + Class repositoryType, Optional detector) { super(qualifiers, repositoryType, beanManager, detector); @@ -63,13 +65,13 @@ class JpaRepositoryBean extends CdiRepositoryBean { * @see org.springframework.data.repository.cdi.CdiRepositoryBean#create(javax.enterprise.context.spi.CreationalContext, java.lang.Class, java.lang.Object) */ @Override - public T create(CreationalContext creationalContext, Class repositoryType, Object customImplementation) { + public T create(CreationalContext creationalContext, Class repositoryType, Optional customImplementation) { // Get an instance from the associated entity manager bean. EntityManager entityManager = getDependencyInstance(entityManagerBean, EntityManager.class); // Create the JPA repository instance and return it. JpaRepositoryFactory factory = new JpaRepositoryFactory(entityManager); - return factory.getRepository(repositoryType, customImplementation); + return customImplementation.isPresent() ? factory.getRepository(repositoryType, customImplementation.get()) : factory.getRepository(repositoryType); } } diff --git a/src/main/java/org/springframework/data/jpa/repository/cdi/JpaRepositoryExtension.java b/src/main/java/org/springframework/data/jpa/repository/cdi/JpaRepositoryExtension.java index eb1a60f52..cc4656573 100644 --- a/src/main/java/org/springframework/data/jpa/repository/cdi/JpaRepositoryExtension.java +++ b/src/main/java/org/springframework/data/jpa/repository/cdi/JpaRepositoryExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import java.util.Set; import javax.enterprise.event.Observes; @@ -42,6 +43,7 @@ import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport; * @author Dirk Mahler * @author Oliver Gierke * @author Mark Paluch + * @author Christoph Strobl */ public class JpaRepositoryExtension extends CdiRepositoryExtensionSupport { @@ -121,6 +123,6 @@ public class JpaRepositoryExtension extends CdiRepositoryExtensionSupport { // Construct and return the repository bean. return new JpaRepositoryBean(beanManager, entityManagerBean, qualifiers, repositoryType, - getCustomImplementationDetector()); + Optional.ofNullable(getCustomImplementationDetector())); } } diff --git a/src/main/java/org/springframework/data/jpa/repository/config/JpaRepositoryConfigExtension.java b/src/main/java/org/springframework/data/jpa/repository/config/JpaRepositoryConfigExtension.java index 307aa005b..575c9350d 100644 --- a/src/main/java/org/springframework/data/jpa/repository/config/JpaRepositoryConfigExtension.java +++ b/src/main/java/org/springframework/data/jpa/repository/config/JpaRepositoryConfigExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2015 the original author or authors. + * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Locale; +import java.util.Optional; import javax.persistence.Entity; import javax.persistence.MappedSuperclass; @@ -59,6 +60,7 @@ import org.springframework.util.StringUtils; * @author Eberhard Wolff * @author Gil Markham * @author Thomas Darimont + * @author Christoph Strobl */ public class JpaRepositoryConfigExtension extends RepositoryConfigurationExtensionSupport { @@ -118,9 +120,8 @@ public class JpaRepositoryConfigExtension extends RepositoryConfigurationExtensi @Override public void postProcess(BeanDefinitionBuilder builder, RepositoryConfigurationSource source) { - String transactionManagerRef = source.getAttribute("transactionManagerRef"); - builder.addPropertyValue("transactionManager", - transactionManagerRef == null ? DEFAULT_TRANSACTION_MANAGER_BEAN_NAME : transactionManagerRef); + Optional transactionManagerRef = source.getAttribute("transactionManagerRef"); + builder.addPropertyValue("transactionManager", transactionManagerRef.orElse(DEFAULT_TRANSACTION_MANAGER_BEAN_NAME)); builder.addPropertyValue("entityManager", getEntityManagerBeanDefinitionFor(source, source.getSource())); builder.addPropertyReference("mappingContext", JPA_MAPPING_CONTEXT_BEAN_NAME); } @@ -145,10 +146,10 @@ public class JpaRepositoryConfigExtension extends RepositoryConfigurationExtensi @Override public void postProcess(BeanDefinitionBuilder builder, XmlRepositoryConfigurationSource config) { - String enableDefaultTransactions = config.getAttribute(ENABLE_DEFAULT_TRANSACTIONS_ATTRIBUTE); + Optional enableDefaultTransactions = config.getAttribute(ENABLE_DEFAULT_TRANSACTIONS_ATTRIBUTE); - if (StringUtils.hasText(enableDefaultTransactions)) { - builder.addPropertyValue(ENABLE_DEFAULT_TRANSACTIONS_ATTRIBUTE, enableDefaultTransactions); + if (enableDefaultTransactions.isPresent() && StringUtils.hasText(enableDefaultTransactions.get())) { + builder.addPropertyValue(ENABLE_DEFAULT_TRANSACTIONS_ATTRIBUTE, enableDefaultTransactions.get()); } } @@ -184,7 +185,7 @@ public class JpaRepositoryConfigExtension extends RepositoryConfigurationExtensi * Creates an anonymous factory to extract the actual {@link javax.persistence.EntityManager} from the * {@link javax.persistence.EntityManagerFactory} bean name reference. * - * @param entityManagerFactoryBeanName + * @param config * @param source * @return */ @@ -204,7 +205,8 @@ public class JpaRepositoryConfigExtension extends RepositoryConfigurationExtensi private static String getEntityManagerBeanRef(RepositoryConfigurationSource config) { - String entityManagerFactoryRef = config == null ? null : config.getAttribute("entityManagerFactoryRef"); - return entityManagerFactoryRef == null ? "entityManagerFactory" : entityManagerFactoryRef; + Optional entityManagerFactoryRef = config == null ? Optional.empty() + : config.getAttribute("entityManagerFactoryRef"); + return entityManagerFactoryRef.orElse("entityManagerFactory"); } } diff --git a/src/main/java/org/springframework/data/jpa/repository/query/AbstractJpaQuery.java b/src/main/java/org/springframework/data/jpa/repository/query/AbstractJpaQuery.java index 2006f12d0..73f53241e 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/AbstractJpaQuery.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/AbstractJpaQuery.java @@ -18,6 +18,7 @@ package org.springframework.data.jpa.repository.query; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.LockModeType; @@ -49,6 +50,7 @@ import org.springframework.util.Assert; * @author Oliver Gierke * @author Thomas Darimont * @author Mark Paluch + * @author Christoph Strobl */ public abstract class AbstractJpaQuery implements RepositoryQuery { @@ -116,7 +118,7 @@ public abstract class AbstractJpaQuery implements RepositoryQuery { Object result = execution.execute(this, values); ParametersParameterAccessor accessor = new ParametersParameterAccessor(method.getParameters(), values); - ResultProcessor withDynamicProjection = method.getResultProcessor().withDynamicProjection(accessor); + ResultProcessor withDynamicProjection = method.getResultProcessor().withDynamicProjection(Optional.of(accessor)); return withDynamicProjection.processResult(result, new TupleConverter(withDynamicProjection.getReturnedType())); } diff --git a/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryExecution.java b/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryExecution.java index 637a5d641..766cca559 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryExecution.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryExecution.java @@ -37,7 +37,6 @@ import org.springframework.data.repository.query.ParameterAccessor; import org.springframework.data.repository.query.Parameters; import org.springframework.data.repository.query.ParametersParameterAccessor; import org.springframework.data.repository.support.PageableExecutionUtils; -import org.springframework.data.repository.support.PageableExecutionUtils.TotalSupplier; import org.springframework.data.util.CloseableIterator; import org.springframework.data.util.StreamUtils; import org.springframework.util.Assert; @@ -51,6 +50,7 @@ import org.springframework.util.ClassUtils; * @author Oliver Gierke * @author Thomas Darimont * @author Mark Paluch + * @author Christoph Strobl */ public abstract class JpaQueryExecution { @@ -106,7 +106,7 @@ public abstract class JpaQueryExecution { * Method to implement {@link AbstractStringBasedJpaQuery} executions by single enum values. * * @param query - * @param binder + * @param values * @return */ protected abstract Object doExecute(AbstractJpaQuery query, Object[] values); @@ -183,18 +183,18 @@ public abstract class JpaQueryExecution { ParameterAccessor accessor = new ParametersParameterAccessor(parameters, values); Query query = repositoryQuery.createQuery(values); - return PageableExecutionUtils.getPage(query.getResultList(), accessor.getPageable(), new TotalSupplier() { + return PageableExecutionUtils.getPage(query.getResultList(), accessor.getPageable(), () -> count(repositoryQuery, values)); - @Override - public long get() { + } - List totals = repositoryQuery.createCountQuery(values).getResultList(); - return (totals.size() == 1 ? CONVERSION_SERVICE.convert(totals.get(0), Long.class) : totals.size()); - } - }); + private long count(AbstractJpaQuery repositoryQuery, Object[] values) { + + List totals = repositoryQuery.createCountQuery(values).getResultList(); + return (totals.size() == 1 ? CONVERSION_SERVICE.convert(totals.get(0), Long.class) : totals.size()); } } + /** * Executes a {@link AbstractStringBasedJpaQuery} to return a single entity. */ @@ -246,7 +246,7 @@ public abstract class JpaQueryExecution { } /** - * {@link Execution} removing entities matching the query. + * {@link JpaQueryExecution} removing entities matching the query. * * @author Thomas Darimont * @author Oliver Gierke @@ -279,7 +279,7 @@ public abstract class JpaQueryExecution { } /** - * {@link Execution} performing an exists check on the query. + * {@link JpaQueryExecution} performing an exists check on the query. * * @author Mark Paluch * @since 1.11 @@ -293,7 +293,7 @@ public abstract class JpaQueryExecution { } /** - * {@link Execution} executing a stored procedure. + * {@link JpaQueryExecution} executing a stored procedure. * * @author Thomas Darimont * @since 1.6 @@ -318,7 +318,7 @@ public abstract class JpaQueryExecution { } /** - * {@link Execution} executing a Java 8 Stream. + * {@link JpaQueryExecution} executing a Java 8 Stream. * * @author Thomas Darimont * @since 1.8 diff --git a/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryMethod.java b/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryMethod.java index af6d5d1dc..7682d9b40 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryMethod.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryMethod.java @@ -113,8 +113,8 @@ public class JpaQueryMethod extends QueryMethod { continue; } - if (!annotatedQuery.contains(String.format(":%s", parameter.getName())) - && !annotatedQuery.contains(String.format("#%s", parameter.getName()))) { + if (!annotatedQuery.contains(String.format(":%s", parameter.getName().get())) + && !annotatedQuery.contains(String.format("#%s", parameter.getName().get()))) { throw new IllegalStateException( String.format("Using named parameters for method %s but parameter '%s' not found in annotated query '%s'!", method, parameter.getName(), annotatedQuery)); diff --git a/src/main/java/org/springframework/data/jpa/repository/query/ParameterBinder.java b/src/main/java/org/springframework/data/jpa/repository/query/ParameterBinder.java index 73dee3da8..1dc96ee1a 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/ParameterBinder.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/ParameterBinder.java @@ -19,6 +19,7 @@ import java.util.Date; import javax.persistence.Query; +import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.query.JpaParameters.JpaParameter; @@ -26,6 +27,7 @@ import org.springframework.data.repository.query.ParameterAccessor; import org.springframework.data.repository.query.Parameters; import org.springframework.data.repository.query.ParametersParameterAccessor; import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; /** * {@link ParameterBinder} is used to bind method parameters to a {@link Query}. This is usually done whenever an @@ -34,6 +36,7 @@ import org.springframework.util.Assert; * @author Oliver Gierke * @author Thomas Darimont * @author Mark Paluch + * @author Christoph Strobl */ public class ParameterBinder { @@ -128,7 +131,7 @@ public class ParameterBinder { if (parameter.isTemporalParameter()) { if (hasNamedParameter(query) && parameter.isNamedParameter()) { - query.setParameter(parameter.getName(), (Date) value, parameter.getTemporalType()); + query.setParameter(parameter.getName().orElseThrow(() -> new IllegalArgumentException("o_O paraneter needs to have a name!")), (Date) value, parameter.getTemporalType()); } else { query.setParameter(position, (Date) value, parameter.getTemporalType()); } @@ -136,7 +139,7 @@ public class ParameterBinder { } if (hasNamedParameter(query) && parameter.isNamedParameter()) { - query.setParameter(parameter.getName(), value); + query.setParameter(parameter.getName().orElseThrow(() -> new IllegalArgumentException("o_O paraneter needs to have a name!")), value); } else { query.setParameter(position, value); } @@ -160,11 +163,12 @@ public class ParameterBinder { Query result = bind(query); - if (!parameters.hasPageableParameter() || getPageable() == null) { + if (!parameters.hasPageableParameter() || getPageable() == null || ObjectUtils.nullSafeEquals(Pageable.NONE, getPageable())) { return result; } - result.setFirstResult(getPageable().getOffset()); + + result.setFirstResult((int) getPageable().getOffset()); result.setMaxResults(getPageable().getPageSize()); return result; diff --git a/src/main/java/org/springframework/data/jpa/repository/query/ParameterMetadataProvider.java b/src/main/java/org/springframework/data/jpa/repository/query/ParameterMetadataProvider.java index 781db7462..5ee7c1a6a 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/ParameterMetadataProvider.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/ParameterMetadataProvider.java @@ -42,6 +42,7 @@ import org.springframework.util.ObjectUtils; * @author Oliver Gierke * @author Thomas Darimont * @author Mark Paluch + * @author Christoph Strobl */ class ParameterMetadataProvider { @@ -159,7 +160,7 @@ class ParameterMetadataProvider { Class reifiedType = Expression.class.equals(type) ? (Class) Object.class : type; ParameterExpression expression = parameter.isExplicitlyNamed() - ? builder.parameter(reifiedType, parameter.getName()) : builder.parameter(reifiedType); + ? builder.parameter(reifiedType, parameter.getName().orElseThrow(() -> new IllegalArgumentException("o_O Parameter needs to be named"))) : builder.parameter(reifiedType); ParameterMetadata value = new ParameterMetadata(expression, part.getType(), bindableParameterValues == null ? ParameterMetadata.PLACEHOLDER : bindableParameterValues.next(), this.persistenceProvider); diff --git a/src/main/java/org/springframework/data/jpa/repository/query/PartTreeJpaQuery.java b/src/main/java/org/springframework/data/jpa/repository/query/PartTreeJpaQuery.java index 707b0a51c..e7b4333d3 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/PartTreeJpaQuery.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/PartTreeJpaQuery.java @@ -16,6 +16,7 @@ package org.springframework.data.jpa.repository.query; import java.util.List; +import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.Query; @@ -37,6 +38,7 @@ import org.springframework.data.repository.query.parser.PartTree; * * @author Oliver Gierke * @author Thomas Darimont + * @author Christoph Strobl */ public class PartTreeJpaQuery extends AbstractJpaQuery { @@ -52,8 +54,8 @@ public class PartTreeJpaQuery extends AbstractJpaQuery { * Creates a new {@link PartTreeJpaQuery}. * * @param method must not be {@literal null}. - * @param factory must not be {@literal null}. * @param em must not be {@literal null}. + * @param persistenceProvider must not be {@literal null}. */ public PartTreeJpaQuery(JpaQueryMethod method, EntityManager em, PersistenceProvider persistenceProvider) { @@ -212,7 +214,7 @@ public class PartTreeJpaQuery extends AbstractJpaQuery { ? new ParameterMetadataProvider(builder, parameters, persistenceProvider) : new ParameterMetadataProvider(builder, accessor, persistenceProvider); - ResultProcessor resultFactory = getQueryMethod().getResultProcessor().withDynamicProjection(accessor); + ResultProcessor resultFactory = getQueryMethod().getResultProcessor().withDynamicProjection(Optional.ofNullable(accessor)); return new JpaQueryCreator(tree, resultFactory.getReturnedType(), builder, provider); } diff --git a/src/main/java/org/springframework/data/jpa/repository/query/StoredProcedureJpaQuery.java b/src/main/java/org/springframework/data/jpa/repository/query/StoredProcedureJpaQuery.java index 8e041c382..0713c074e 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/StoredProcedureJpaQuery.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/StoredProcedureJpaQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,6 +33,7 @@ import org.springframework.util.StringUtils; * * @author Thomas Darimont * @author Oliver Gierke + * @author Christoph Strobl * @since 1.6 */ class StoredProcedureJpaQuery extends AbstractJpaQuery { @@ -158,7 +159,7 @@ class StoredProcedureJpaQuery extends AbstractJpaQuery { } if (useNamedParameters) { - procedureQuery.registerStoredProcedureParameter(param.getName(), param.getType(), ParameterMode.IN); + procedureQuery.registerStoredProcedureParameter(param.getName().orElseThrow(() -> new IllegalArgumentException("Parameter needs to be named!")), param.getType(), ParameterMode.IN); } else { procedureQuery.registerStoredProcedureParameter(param.getIndex() + 1, param.getType(), ParameterMode.IN); } diff --git a/src/main/java/org/springframework/data/jpa/repository/query/StringQueryParameterBinder.java b/src/main/java/org/springframework/data/jpa/repository/query/StringQueryParameterBinder.java index b3fc87b6a..8fcb899aa 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/StringQueryParameterBinder.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/StringQueryParameterBinder.java @@ -29,6 +29,7 @@ import org.springframework.util.Assert; * * @author Oliver Gierke * @author Thomas Darimont + * @author Christoph Strobl */ public class StringQueryParameterBinder extends ParameterBinder { @@ -72,7 +73,7 @@ public class StringQueryParameterBinder extends ParameterBinder { private ParameterBinding getBindingFor(Query jpaQuery, int position, Parameter methodParameter) { if (hasNamedParameter(jpaQuery)) { - return query.getBindingFor(methodParameter.getName()); + return query.getBindingFor(methodParameter.getName().orElseThrow(() -> new IllegalArgumentException("Parameter needs to be named!"))); } try { diff --git a/src/main/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformation.java b/src/main/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformation.java index 22b693c96..1f1e5e427 100644 --- a/src/main/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformation.java +++ b/src/main/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformation.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; +import java.util.Optional; import java.util.Set; import javax.persistence.IdClass; @@ -141,12 +142,12 @@ public class JpaMetamodelEntityInformation extends J * @see org.springframework.data.repository.core.EntityInformation#getId(java.lang.Object) */ @SuppressWarnings("unchecked") - public ID getId(T entity) { + public Optional getId(T entity) { BeanWrapper entityWrapper = new DirectFieldAccessFallbackBeanWrapper(entity); if (idMetadata.hasSimpleId()) { - return (ID) entityWrapper.getPropertyValue(idMetadata.getSimpleIdAttribute().getName()); + return Optional.ofNullable((ID)entityWrapper.getPropertyValue(idMetadata.getSimpleIdAttribute().getName())); } BeanWrapper idWrapper = new IdentifierDerivingDirectFieldAccessFallbackBeanWrapper(idMetadata.getType(), metamodel); @@ -162,7 +163,7 @@ public class JpaMetamodelEntityInformation extends J idWrapper.setPropertyValue(attribute.getName(), propertyValue); } - return (ID) (partialIdValueFound ? idWrapper.getWrappedInstance() : null); + return partialIdValueFound ? Optional.ofNullable((ID)idWrapper.getWrappedInstance()) : Optional.empty(); } /* @@ -318,9 +319,7 @@ public class JpaMetamodelEntityInformation extends J /** * In addition to the functionality described in {@link BeanWrapperImpl} it is checked whether we have a nested * entity that is part of the id key. If this is the case, we need to derive the identifier of the nested entity. - * - * @see org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.DirectFieldAccessFallbackBeanWrapper#setPropertyValue(java.lang.String, - * java.lang.Object) + * */ @Override public void setPropertyValue(String propertyName, Object value) { diff --git a/src/main/java/org/springframework/data/jpa/repository/support/JpaPersistableEntityInformation.java b/src/main/java/org/springframework/data/jpa/repository/support/JpaPersistableEntityInformation.java index c7b1371c1..6c616117b 100644 --- a/src/main/java/org/springframework/data/jpa/repository/support/JpaPersistableEntityInformation.java +++ b/src/main/java/org/springframework/data/jpa/repository/support/JpaPersistableEntityInformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2013 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package org.springframework.data.jpa.repository.support; import java.io.Serializable; +import java.util.Optional; import javax.persistence.metamodel.Metamodel; @@ -25,6 +26,7 @@ import org.springframework.data.domain.Persistable; * Extension of {@link JpaMetamodelEntityInformation} that consideres methods of {@link Persistable} to lookup the id. * * @author Oliver Gierke + * @author Christoph Strobl */ public class JpaPersistableEntityInformation, ID extends Serializable> extends JpaMetamodelEntityInformation { @@ -53,7 +55,7 @@ public class JpaPersistableEntityInformation, ID exten * @see org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation#getId(java.lang.Object) */ @Override - public ID getId(T entity) { - return entity.getId(); + public Optional getId(T entity) { + return Optional.ofNullable(entity.getId()); } } diff --git a/src/main/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactory.java b/src/main/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactory.java index a4a2bfa84..373f8f3d6 100644 --- a/src/main/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactory.java +++ b/src/main/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactory.java @@ -15,9 +15,10 @@ */ package org.springframework.data.jpa.repository.support; -import static org.springframework.data.querydsl.QueryDslUtils.*; +import static org.springframework.data.querydsl.QuerydslUtils.*; import java.io.Serializable; +import java.util.Optional; import javax.persistence.EntityManager; @@ -25,7 +26,7 @@ import org.springframework.data.jpa.provider.PersistenceProvider; import org.springframework.data.jpa.provider.QueryExtractor; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.core.RepositoryInformation; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.RepositoryFactorySupport; @@ -39,6 +40,7 @@ import org.springframework.util.Assert; * * @author Oliver Gierke * @author Mark Paluch + * @author Christoph Strobl */ public class JpaRepositoryFactory extends RepositoryFactorySupport { @@ -91,7 +93,6 @@ public class JpaRepositoryFactory extends RepositoryFactorySupport { * @param * @param * @param entityManager - * @see #getTargetRepository(RepositoryMetadata) * @return */ protected SimpleJpaRepository getTargetRepository( @@ -113,7 +114,7 @@ public class JpaRepositoryFactory extends RepositoryFactorySupport { protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { if (isQueryDslExecutor(metadata.getRepositoryInterface())) { - return QueryDslJpaRepository.class; + return QuerydslJpaRepository.class; } else { return SimpleJpaRepository.class; } @@ -127,7 +128,7 @@ public class JpaRepositoryFactory extends RepositoryFactorySupport { */ private boolean isQueryDslExecutor(Class repositoryInterface) { - return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface); + return QUERY_DSL_PRESENT && QuerydslPredicateExecutor.class.isAssignableFrom(repositoryInterface); } /* @@ -135,8 +136,8 @@ public class JpaRepositoryFactory extends RepositoryFactorySupport { * @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getQueryLookupStrategy(org.springframework.data.repository.query.QueryLookupStrategy.Key, org.springframework.data.repository.query.EvaluationContextProvider) */ @Override - protected QueryLookupStrategy getQueryLookupStrategy(Key key, EvaluationContextProvider evaluationContextProvider) { - return JpaQueryLookupStrategy.create(entityManager, key, extractor, evaluationContextProvider); + protected Optional getQueryLookupStrategy(Key key, EvaluationContextProvider evaluationContextProvider) { + return Optional.of(JpaQueryLookupStrategy.create(entityManager, key, extractor, evaluationContextProvider)); } /* diff --git a/src/main/java/org/springframework/data/jpa/repository/support/Querydsl.java b/src/main/java/org/springframework/data/jpa/repository/support/Querydsl.java index 9ad51732b..07f961763 100644 --- a/src/main/java/org/springframework/data/jpa/repository/support/Querydsl.java +++ b/src/main/java/org/springframework/data/jpa/repository/support/Querydsl.java @@ -40,6 +40,7 @@ import com.querydsl.jpa.JPQLQuery; import com.querydsl.jpa.OpenJPATemplates; import com.querydsl.jpa.impl.AbstractJPAQuery; import com.querydsl.jpa.impl.JPAQuery; +import org.springframework.util.ObjectUtils; /** * Helper instance to ease access to Querydsl JPA query API. @@ -47,6 +48,7 @@ import com.querydsl.jpa.impl.JPAQuery; * @author Oliver Gierke * @author Thomas Darimont * @author Mark Paluch + * @author Christoph Strobl */ public class Querydsl { @@ -108,7 +110,7 @@ public class Querydsl { */ public JPQLQuery applyPagination(Pageable pageable, JPQLQuery query) { - if (pageable == null) { + if (pageable == null || ObjectUtils.nullSafeEquals(Pageable.NONE, pageable)) { return query; } diff --git a/src/main/java/org/springframework/data/jpa/repository/support/QueryDslJpaRepository.java b/src/main/java/org/springframework/data/jpa/repository/support/QuerydslJpaRepository.java similarity index 89% rename from src/main/java/org/springframework/data/jpa/repository/support/QueryDslJpaRepository.java rename to src/main/java/org/springframework/data/jpa/repository/support/QuerydslJpaRepository.java index c1a59fb7a..170a74c81 100644 --- a/src/main/java/org/springframework/data/jpa/repository/support/QueryDslJpaRepository.java +++ b/src/main/java/org/springframework/data/jpa/repository/support/QuerydslJpaRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2016 the original author or authors. + * Copyright 2008-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,10 +27,9 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.querydsl.EntityPathResolver; import org.springframework.data.querydsl.QSort; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.querydsl.SimpleEntityPathResolver; import org.springframework.data.repository.support.PageableExecutionUtils; -import org.springframework.data.repository.support.PageableExecutionUtils.TotalSupplier; import com.querydsl.core.types.EntityPath; import com.querydsl.core.types.OrderSpecifier; @@ -41,15 +40,16 @@ import com.querydsl.jpa.impl.AbstractJPAQuery; /** * QueryDsl specific extension of {@link SimpleJpaRepository} which adds implementation for - * {@link QueryDslPredicateExecutor}. + * {@link QuerydslPredicateExecutor}. * * @author Oliver Gierke * @author Thomas Darimont * @author Mark Paluch * @author Jocelyn Ntakpe + * @author Christoph Strobl */ -public class QueryDslJpaRepository extends SimpleJpaRepository - implements QueryDslPredicateExecutor { +public class QuerydslJpaRepository extends SimpleJpaRepository + implements QuerydslPredicateExecutor { private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE; @@ -58,26 +58,26 @@ public class QueryDslJpaRepository extends SimpleJpa private final Querydsl querydsl; /** - * Creates a new {@link QueryDslJpaRepository} from the given domain class and {@link EntityManager}. This will use + * Creates a new {@link QuerydslJpaRepository} from the given domain class and {@link EntityManager}. This will use * the {@link SimpleEntityPathResolver} to translate the given domain class into an {@link EntityPath}. * * @param entityInformation must not be {@literal null}. * @param entityManager must not be {@literal null}. */ - public QueryDslJpaRepository(JpaEntityInformation entityInformation, EntityManager entityManager) { + public QuerydslJpaRepository(JpaEntityInformation entityInformation, EntityManager entityManager) { this(entityInformation, entityManager, DEFAULT_ENTITY_PATH_RESOLVER); } /** - * Creates a new {@link QueryDslJpaRepository} from the given domain class and {@link EntityManager} and uses the + * Creates a new {@link QuerydslJpaRepository} from the given domain class and {@link EntityManager} and uses the * given {@link EntityPathResolver} to translate the domain class into an {@link EntityPath}. * * @param entityInformation must not be {@literal null}. * @param entityManager must not be {@literal null}. * @param resolver must not be {@literal null}. */ - public QueryDslJpaRepository(JpaEntityInformation entityInformation, EntityManager entityManager, - EntityPathResolver resolver) { + public QuerydslJpaRepository(JpaEntityInformation entityInformation, EntityManager entityManager, + EntityPathResolver resolver) { super(entityInformation, entityManager); @@ -141,13 +141,7 @@ public class QueryDslJpaRepository extends SimpleJpa final JPQLQuery countQuery = createCountQuery(predicate); JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate).select(path)); - return PageableExecutionUtils.getPage(query.fetch(), pageable, new TotalSupplier() { - - @Override - public long get() { - return countQuery.fetchCount(); - } - }); + return PageableExecutionUtils.getPage(query.fetch(), pageable == null ? Pageable.NONE : pageable, () -> countQuery.fetchCount()); } /* diff --git a/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java b/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java index 25d790ce5..14382e5e0 100644 --- a/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java +++ b/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java @@ -24,6 +24,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.LockModeType; @@ -55,10 +56,10 @@ import org.springframework.data.jpa.repository.query.Jpa21Utils; import org.springframework.data.jpa.repository.query.JpaEntityGraph; import org.springframework.data.jpa.repository.query.QueryUtils; import org.springframework.data.repository.support.PageableExecutionUtils; -import org.springframework.data.repository.support.PageableExecutionUtils.TotalSupplier; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; /** * Default implementation of the {@link org.springframework.data.repository.CrudRepository} interface. This will offer @@ -68,6 +69,7 @@ import org.springframework.util.Assert; * @author Eberhard Wolff * @author Thomas Darimont * @author Mark Paluch + * @author Christoph Strobl * @param the type of the entity to handle * @param the type of the entity's identifier */ @@ -147,14 +149,8 @@ public class SimpleJpaRepository Assert.notNull(id, ID_MUST_NOT_BE_NULL); - T entity = findOne(id); - - if (entity == null) { - throw new EmptyResultDataAccessException( - String.format("No %s entity with id %s exists!", entityInformation.getJavaType(), id), 1); - } - - delete(entity); + delete(findOne(id).orElseThrow(() -> new EmptyResultDataAccessException( + String.format("No %s entity with id %s exists!", entityInformation.getJavaType(), id), 1))); } /* @@ -224,21 +220,21 @@ public class SimpleJpaRepository * (non-Javadoc) * @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable) */ - public T findOne(ID id) { + public Optional findOne(ID id) { Assert.notNull(id, ID_MUST_NOT_BE_NULL); Class domainType = getDomainClass(); if (metadata == null) { - return em.find(domainType, id); + return Optional.ofNullable(em.find(domainType, id)); } LockModeType type = metadata.getLockModeType(); Map hints = getQueryHints(); - return type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints); + return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints)); } /** @@ -344,7 +340,7 @@ public class SimpleJpaRepository List results = new ArrayList(); for (ID id : ids) { - results.add(findOne(id)); + findOne(id).ifPresent(results::add); } return results; @@ -583,16 +579,14 @@ public class SimpleJpaRepository protected Page readPage(TypedQuery query, final Class domainClass, Pageable pageable, final Specification spec) { - query.setFirstResult(pageable.getOffset()); - query.setMaxResults(pageable.getPageSize()); + if (!ObjectUtils.nullSafeEquals(Pageable.NONE, pageable)) { - return PageableExecutionUtils.getPage(query.getResultList(), pageable, new TotalSupplier() { + query.setFirstResult((int) pageable.getOffset()); + query.setMaxResults(pageable.getPageSize()); + } - @Override - public long get() { - return executeCountQuery(getCountQuery(spec, domainClass)); - } - }); + return PageableExecutionUtils.getPage(query.getResultList(), pageable, + () -> executeCountQuery(getCountQuery(spec, domainClass))); } /** @@ -649,7 +643,7 @@ public class SimpleJpaRepository Root root = applySpecificationToCriteria(spec, domainClass, query); query.select(root); - if (sort != null) { + if (sort != null && !ObjectUtils.nullSafeEquals(sort, Sort.unsorted())) { query.orderBy(toOrders(sort, root, builder)); } diff --git a/src/test/java/org/springframework/data/jpa/domain/sample/AuditableUser.java b/src/test/java/org/springframework/data/jpa/domain/sample/AuditableUser.java index c3267d1a3..5eef4acce 100644 --- a/src/test/java/org/springframework/data/jpa/domain/sample/AuditableUser.java +++ b/src/test/java/org/springframework/data/jpa/domain/sample/AuditableUser.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2015 the original author or authors. + * Copyright 2008-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package org.springframework.data.jpa.domain.sample; +import java.time.Instant; import java.util.HashSet; import java.util.Set; diff --git a/src/test/java/org/springframework/data/jpa/domain/sample/AuditorAwareStub.java b/src/test/java/org/springframework/data/jpa/domain/sample/AuditorAwareStub.java index bbfc3314a..a4acfada5 100644 --- a/src/test/java/org/springframework/data/jpa/domain/sample/AuditorAwareStub.java +++ b/src/test/java/org/springframework/data/jpa/domain/sample/AuditorAwareStub.java @@ -15,6 +15,8 @@ */ package org.springframework.data.jpa.domain.sample; +import java.util.Optional; + import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.repository.sample.AuditableUserRepository; import org.springframework.util.Assert; @@ -47,8 +49,8 @@ public class AuditorAwareStub implements AuditorAware { * * @see org.springframework.data.domain.AuditorAware#getCurrentAuditor() */ - public AuditableUser getCurrentAuditor() { + public Optional getCurrentAuditor() { - return auditor; + return Optional.ofNullable(auditor); } } diff --git a/src/test/java/org/springframework/data/jpa/domain/support/AuditingEntityListenerTests.java b/src/test/java/org/springframework/data/jpa/domain/support/AuditingEntityListenerTests.java index 774193814..b5f19e01a 100644 --- a/src/test/java/org/springframework/data/jpa/domain/support/AuditingEntityListenerTests.java +++ b/src/test/java/org/springframework/data/jpa/domain/support/AuditingEntityListenerTests.java @@ -18,6 +18,10 @@ package org.springframework.data.jpa.domain.support; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.Optional; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -76,7 +80,7 @@ public class AuditingEntityListenerTests { user = repository.saveAndFlush(user); - assertThat(user.getCreatedDate().isBefore(user.getLastModifiedDate()), is(true)); + assertThat(user.getCreatedDate().get().isBefore(user.getLastModifiedDate().get()), is(true)); } @Test @@ -104,15 +108,15 @@ public class AuditingEntityListenerTests { assertThat(auditableUser.getLastModifiedBy(), is(notNullValue())); } - private static void assertDatesSet(Auditable auditable) { + private static void assertDatesSet(Auditable auditable) { - assertThat(auditable.getCreatedDate(), is(notNullValue())); - assertThat(auditable.getLastModifiedDate(), is(notNullValue())); + assertThat(auditable.getCreatedDate().isPresent(), is(true)); + assertThat(auditable.getLastModifiedDate().isPresent(), is(true)); } - private static void assertUserIsAuditor(AuditableUser user, Auditable auditable) { + private static void assertUserIsAuditor(AuditableUser user, Auditable auditable) { - assertThat(auditable.getCreatedBy(), is(user)); - assertThat(auditable.getLastModifiedBy(), is(user)); + assertThat(auditable.getCreatedBy(), is(Optional.of(user))); + assertThat(auditable.getLastModifiedBy(), is(Optional.of(user))); } } diff --git a/src/test/java/org/springframework/data/jpa/mapping/JpaMetamodelMappingContextIntegrationTests.java b/src/test/java/org/springframework/data/jpa/mapping/JpaMetamodelMappingContextIntegrationTests.java index 6a516dad8..07aac65f0 100644 --- a/src/test/java/org/springframework/data/jpa/mapping/JpaMetamodelMappingContextIntegrationTests.java +++ b/src/test/java/org/springframework/data/jpa/mapping/JpaMetamodelMappingContextIntegrationTests.java @@ -19,6 +19,7 @@ import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.util.Collections; +import java.util.Optional; import javax.persistence.EntityManager; @@ -79,47 +80,47 @@ public class JpaMetamodelMappingContextIntegrationTests { @Test public void setsUpMappingContextCorrectly() { - JpaPersistentEntityImpl entity = context.getPersistentEntity(User.class); + JpaPersistentEntityImpl entity = context.getRequiredPersistentEntity(User.class); assertThat(entity, is(notNullValue())); } @Test public void detectsIdProperty() { - JpaPersistentEntityImpl entity = context.getPersistentEntity(User.class); + JpaPersistentEntityImpl entity = context.getRequiredPersistentEntity(User.class); assertThat(entity.getIdProperty(), is(notNullValue())); } @Test public void detectsAssociation() { - JpaPersistentEntityImpl entity = context.getPersistentEntity(User.class); + JpaPersistentEntityImpl entity = context.getRequiredPersistentEntity(User.class); assertThat(entity, is(notNullValue())); - JpaPersistentProperty property = entity.getPersistentProperty("manager"); + JpaPersistentProperty property = entity.getRequiredPersistentProperty("manager"); assertThat(property.isAssociation(), is(true)); } @Test public void detectsPropertyIsEntity() { - JpaPersistentEntityImpl entity = context.getPersistentEntity(User.class); + JpaPersistentEntityImpl entity = context.getRequiredPersistentEntity(User.class); assertThat(entity, is(notNullValue())); - JpaPersistentProperty property = entity.getPersistentProperty("manager"); + JpaPersistentProperty property = entity.getRequiredPersistentProperty("manager"); assertThat(property.isEntity(), is(true)); - property = entity.getPersistentProperty("lastname"); + property = entity.getRequiredPersistentProperty("lastname"); assertThat(property.isEntity(), is(false)); } @Test // DATAJPA-608 public void detectsEntityPropertyForCollections() { - JpaPersistentEntityImpl entity = context.getPersistentEntity(User.class); + JpaPersistentEntityImpl entity = context.getRequiredPersistentEntity(User.class); assertThat(entity, is(notNullValue())); - assertThat(entity.getPersistentProperty("colleagues").isEntity(), is(true)); + assertThat(entity.getRequiredPersistentProperty("colleagues").isEntity(), is(true)); } @Test // DATAJPA-630 @@ -141,13 +142,13 @@ public class JpaMetamodelMappingContextIntegrationTests { @Override public Void doInTransaction(TransactionStatus status) { - Category loaded = categories.findOne(category.getId()); + Category loaded = categories.findOne(category.getId()).get(); Product loadedProduct = loaded.getProduct(); - JpaPersistentEntity entity = context.getPersistentEntity(Product.class); + JpaPersistentEntity entity = context.getRequiredPersistentEntity(Product.class); IdentifierAccessor accessor = entity.getIdentifierAccessor(loadedProduct); - assertThat(accessor.getIdentifier(), is((Object) category.getProduct().getId())); + assertThat(accessor.getIdentifier(), is(Optional.of(category.getProduct().getId()))); assertThat(loadedProduct, is(instanceOf(HibernateProxy.class))); assertThat(((HibernateProxy) loadedProduct).getHibernateLazyInitializer().isUninitialized(), is(true)); diff --git a/src/test/java/org/springframework/data/jpa/mapping/JpaPersistentPropertyImplUnitTests.java b/src/test/java/org/springframework/data/jpa/mapping/JpaPersistentPropertyImplUnitTests.java index c0c5965af..04c7e4c64 100644 --- a/src/test/java/org/springframework/data/jpa/mapping/JpaPersistentPropertyImplUnitTests.java +++ b/src/test/java/org/springframework/data/jpa/mapping/JpaPersistentPropertyImplUnitTests.java @@ -20,6 +20,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.Collections; +import java.util.Optional; import javax.persistence.Access; import javax.persistence.AccessType; @@ -60,19 +61,19 @@ public class JpaPersistentPropertyImplUnitTests { public void setUp() { context = new JpaMetamodelMappingContext(Collections.singleton(model)); - entity = context.getPersistentEntity(Sample.class); + entity = context.getRequiredPersistentEntity(Sample.class); } @Test // DATAJPA-284 public void considersOneToOneMappedPropertyAnAssociation() { - JpaPersistentProperty property = entity.getPersistentProperty("other"); + JpaPersistentProperty property = entity.getRequiredPersistentProperty("other"); assertThat(property.isAssociation(), is(true)); } @Test // DATAJPA-376 public void considersJpaTransientFieldsAsTransient() { - assertThat(entity.getPersistentProperty("transientProp"), is(nullValue())); + assertThat(entity.getPersistentProperty("transientProp"), is(Optional.empty())); } @Test // DATAJPA-484 @@ -82,12 +83,12 @@ public class JpaPersistentPropertyImplUnitTests { @Test // DATAJPA-484 public void considersEmbeddablePropertyAnAssociation() { - assertThat(entity.getPersistentProperty("embeddable").isAssociation(), is(true)); + assertThat(entity.getRequiredPersistentProperty("embeddable").isAssociation(), is(true)); } @Test // DATAJPA-484 public void considersEmbeddedPropertyAnAssociation() { - assertThat(entity.getPersistentProperty("embedded").isAssociation(), is(true)); + assertThat(entity.getRequiredPersistentProperty("embedded").isAssociation(), is(true)); } @Test // DATAJPA-619 @@ -158,8 +159,8 @@ public class JpaPersistentPropertyImplUnitTests { private JpaPersistentProperty getProperty(Class ownerType, String propertyName) { - JpaPersistentEntity entity = context.getPersistentEntity(ownerType); - return entity.getPersistentProperty(propertyName); + JpaPersistentEntity entity = context.getRequiredPersistentEntity(ownerType); + return entity.getRequiredPersistentProperty(propertyName); } static class Sample { diff --git a/src/test/java/org/springframework/data/jpa/provider/PersistenceProviderIntegrationTests.java b/src/test/java/org/springframework/data/jpa/provider/PersistenceProviderIntegrationTests.java index 4b0ee12b3..fb58a31f2 100644 --- a/src/test/java/org/springframework/data/jpa/provider/PersistenceProviderIntegrationTests.java +++ b/src/test/java/org/springframework/data/jpa/provider/PersistenceProviderIntegrationTests.java @@ -82,7 +82,7 @@ public class PersistenceProviderIntegrationTests { @Override public Void doInTransaction(TransactionStatus status) { - Product product = categories.findOne(category.getId()).getProduct(); + Product product = categories.findOne(category.getId()).get().getProduct(); ProxyIdAccessor accessor = PersistenceProvider.fromEntityManager(em); assertThat(accessor.shouldUseAccessorFor(product), is(true)); diff --git a/src/test/java/org/springframework/data/jpa/repository/AbstractPersistableIntegrationTests.java b/src/test/java/org/springframework/data/jpa/repository/AbstractPersistableIntegrationTests.java index 33eb12b68..307ff1dda 100644 --- a/src/test/java/org/springframework/data/jpa/repository/AbstractPersistableIntegrationTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/AbstractPersistableIntegrationTests.java @@ -49,7 +49,7 @@ public class AbstractPersistableIntegrationTests { CustomAbstractPersistable entity = new CustomAbstractPersistable(); CustomAbstractPersistable saved = repository.save(entity); - CustomAbstractPersistable found = repository.findOne(saved.getId()); + CustomAbstractPersistable found = repository.findOne(saved.getId()).get(); assertThat(found, is(saved)); } diff --git a/src/test/java/org/springframework/data/jpa/repository/CustomAbstractPersistableIntegrationTests.java b/src/test/java/org/springframework/data/jpa/repository/CustomAbstractPersistableIntegrationTests.java index 0bc1d90e3..5b58ff498 100644 --- a/src/test/java/org/springframework/data/jpa/repository/CustomAbstractPersistableIntegrationTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/CustomAbstractPersistableIntegrationTests.java @@ -43,7 +43,7 @@ public class CustomAbstractPersistableIntegrationTests { CustomAbstractPersistable entity = new CustomAbstractPersistable(); CustomAbstractPersistable saved = repository.save(entity); - CustomAbstractPersistable found = repository.findOne(saved.getId()); + CustomAbstractPersistable found = repository.findOne(saved.getId()).get(); assertThat(found, is(saved)); } diff --git a/src/test/java/org/springframework/data/jpa/repository/EntityGraphRepositoryMethodsIntegrationTests.java b/src/test/java/org/springframework/data/jpa/repository/EntityGraphRepositoryMethodsIntegrationTests.java index eae38c5b9..9965f8959 100644 --- a/src/test/java/org/springframework/data/jpa/repository/EntityGraphRepositoryMethodsIntegrationTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/EntityGraphRepositoryMethodsIntegrationTests.java @@ -101,7 +101,7 @@ public class EntityGraphRepositoryMethodsIntegrationTests { Assume.assumeTrue(currentEntityManagerIsAJpa21EntityManager(em)); - User user = repository.findOne(tom.getId()); + User user = repository.findOne(tom.getId()).get(); assertThat(user, is(notNullValue())); assertThat("colleages should be fetched with 'user.detail' fetchgraph", util.isLoaded(user, "colleagues"), diff --git a/src/test/java/org/springframework/data/jpa/repository/RepositoryWithCompositeKeyTests.java b/src/test/java/org/springframework/data/jpa/repository/RepositoryWithCompositeKeyTests.java index a22e07ce2..e57dd9c9c 100644 --- a/src/test/java/org/springframework/data/jpa/repository/RepositoryWithCompositeKeyTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/RepositoryWithCompositeKeyTests.java @@ -80,7 +80,7 @@ public class RepositoryWithCompositeKeyTests { IdClassExampleEmployeePK key = new IdClassExampleEmployeePK(); key.setDepartment(dep.getDepartmentId()); key.setEmpId(emp.getEmpId()); - IdClassExampleEmployee persistedEmp = employeeRepositoryWithIdClass.findOne(key); + IdClassExampleEmployee persistedEmp = employeeRepositoryWithIdClass.findOne(key).get(); assertThat(persistedEmp, is(notNullValue())); assertThat(persistedEmp.getDepartment(), is(notNullValue())); @@ -107,7 +107,7 @@ public class RepositoryWithCompositeKeyTests { EmbeddedIdExampleEmployeePK key = new EmbeddedIdExampleEmployeePK(); key.setDepartmentId(emp.getDepartment().getDepartmentId()); key.setEmployeeId(emp.getEmployeePk().getEmployeeId()); - EmbeddedIdExampleEmployee persistedEmp = employeeRepositoryWithEmbeddedId.findOne(key); + EmbeddedIdExampleEmployee persistedEmp = employeeRepositoryWithEmbeddedId.findOne(key).get(); assertThat(persistedEmp, is(notNullValue())); assertThat(persistedEmp.getDepartment(), is(notNullValue())); @@ -278,8 +278,8 @@ public class RepositoryWithCompositeKeyTests { emp1PK.setEmpId(3L); IdClassExampleEmployeePK emp2PK = new IdClassExampleEmployeePK(); - emp1PK.setDepartment(1L); - emp1PK.setEmpId(2L); + emp2PK.setDepartment(1L); + emp2PK.setEmpId(2L); List result = employeeRepositoryWithIdClass.findAll(Arrays.asList(emp1PK, emp2PK)); diff --git a/src/test/java/org/springframework/data/jpa/repository/RepositoryWithIdClassKeyTests.java b/src/test/java/org/springframework/data/jpa/repository/RepositoryWithIdClassKeyTests.java index bafc01319..7c0b79bb1 100644 --- a/src/test/java/org/springframework/data/jpa/repository/RepositoryWithIdClassKeyTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/RepositoryWithIdClassKeyTests.java @@ -18,6 +18,8 @@ package org.springframework.data.jpa.repository; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; +import java.util.Optional; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -81,9 +83,10 @@ public class RepositoryWithIdClassKeyTests { itemSiteRepository.save(new ItemSite(item, site)); - ItemSite loaded = itemSiteRepository + Optional loaded = itemSiteRepository .findOne(new ItemSiteId(new ItemId(item.getId(), item.getManufacturerId()), site.getId())); assertThat(loaded, is(notNullValue())); + assertThat(loaded.isPresent(), is(true)); } } diff --git a/src/test/java/org/springframework/data/jpa/repository/RoleRepositoryIntegrationTests.java b/src/test/java/org/springframework/data/jpa/repository/RoleRepositoryIntegrationTests.java index 83900284b..512560f85 100644 --- a/src/test/java/org/springframework/data/jpa/repository/RoleRepositoryIntegrationTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/RoleRepositoryIntegrationTests.java @@ -18,6 +18,8 @@ package org.springframework.data.jpa.repository; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; +import java.util.Optional; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -60,7 +62,7 @@ public class RoleRepositoryIntegrationTests { ReflectionTestUtils.setField(reference, "name", "USER"); repository.save(reference); - assertThat(repository.findOne(result.getId()), is(reference)); + assertThat(repository.findOne(result.getId()), is(Optional.of(reference))); } @Test // DATAJPA-509 diff --git a/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java b/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java index 08d0ce0b6..1ab60abed 100644 --- a/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java @@ -137,7 +137,7 @@ public class UserRepositoryTests { flushTestUsers(); - User foundPerson = repository.findOne(id); + User foundPerson = repository.findOne(id).get(); assertThat(firstUser.getFirstname(), is(foundPerson.getFirstname())); } @@ -155,7 +155,7 @@ public class UserRepositoryTests { flushTestUsers(); - assertThat(repository.findOne(id * 27), is(nullValue())); + assertThat(repository.findOne(id * 27), is(java.util.Optional.empty())); } @Test @@ -188,10 +188,10 @@ public class UserRepositoryTests { flushTestUsers(); - User foundPerson = repository.findOne(id); + User foundPerson = repository.findOne(id).get(); foundPerson.setLastname("Schlicht"); - User updatedPerson = repository.findOne(id); + User updatedPerson = repository.findOne(id).get(); assertThat(updatedPerson.getFirstname(), is(foundPerson.getFirstname())); } @@ -210,7 +210,7 @@ public class UserRepositoryTests { repository.delete(firstUser.getId()); assertThat(repository.exists(id), is(false)); - assertThat(repository.findOne(id), is(nullValue())); + assertThat(repository.findOne(id), is(java.util.Optional.empty())); } @Test @@ -220,7 +220,7 @@ public class UserRepositoryTests { repository.delete(firstUser); assertThat(repository.exists(id), is(false)); - assertThat(repository.findOne(id), is(nullValue())); + assertThat(repository.findOne(id), is(java.util.Optional.empty())); } @Test @@ -379,7 +379,7 @@ public class UserRepositoryTests { flushTestUsers(); // Fetches first user from database - User firstReferenceUser = repository.findOne(firstUser.getId()); + User firstReferenceUser = repository.findOne(firstUser.getId()).get(); assertThat(firstReferenceUser, is(firstUser)); // Fetch colleagues and assert link @@ -411,7 +411,7 @@ public class UserRepositoryTests { firstUser.addColleague(new User("Florian", "Hopf", "hopf@synyx.de")); firstUser = repository.save(firstUser); - User reference = repository.findOne(firstUser.getId()); + User reference = repository.findOne(firstUser.getId()).get(); Set colleagues = reference.getColleagues(); assertThat(colleagues, is(notNullValue())); diff --git a/src/test/java/org/springframework/data/jpa/repository/config/AbstractAuditingViaJavaConfigRepositoriesTests.java b/src/test/java/org/springframework/data/jpa/repository/config/AbstractAuditingViaJavaConfigRepositoriesTests.java index 131ab74c7..5d1f80af1 100644 --- a/src/test/java/org/springframework/data/jpa/repository/config/AbstractAuditingViaJavaConfigRepositoriesTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/config/AbstractAuditingViaJavaConfigRepositoriesTests.java @@ -19,8 +19,12 @@ import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.Date; import java.util.List; +import java.util.Optional; import java.util.concurrent.TimeUnit; import javax.persistence.EntityManager; @@ -30,6 +34,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -76,13 +81,14 @@ public abstract class AbstractAuditingViaJavaConfigRepositoriesTests { AuditableUser auditor = new AuditableUser(null); auditor.setFirstname("auditor"); + when(this.auditorAware.getCurrentAuditor()).thenReturn(Optional.empty()); this.auditor = this.auditableUserRepository.save(auditor); - doReturn(this.auditor).when(this.auditorAware).getCurrentAuditor(); + when(this.auditorAware.getCurrentAuditor()).thenReturn(Optional.of(this.auditor)); } @After public void teardown() { - doReturn(null).when(this.auditorAware).getCurrentAuditor(); + Mockito.reset(this.auditorAware); } @Test @@ -95,9 +101,9 @@ public abstract class AbstractAuditingViaJavaConfigRepositoriesTests { TimeUnit.MILLISECONDS.sleep(10); assertThat(savedUser.getCreatedDate(), is(notNullValue())); - assertThat(savedUser.getCreatedDate().isBeforeNow(), is(true)); + assertThat(savedUser.getCreatedDate().get().isBefore(LocalDateTime.now()), is(true)); - AuditableUser createdBy = savedUser.getCreatedBy(); + AuditableUser createdBy = savedUser.getCreatedBy().get(); assertThat(createdBy, is(notNullValue())); assertThat(createdBy.getFirstname(), is(this.auditor.getFirstname())); } @@ -119,14 +125,15 @@ public abstract class AbstractAuditingViaJavaConfigRepositoriesTests { SampleSecurityContextHolder.getCurrent().setPrincipal(thomas); auditableUserRepository.updateAllNamesToUpperCase(); - DateTime now = new DateTime(FixedDate.INSTANCE.getDate()); +// DateTime now = new DateTime(FixedDate.INSTANCE.getDate()); + LocalDateTime now = LocalDateTime.ofInstant(FixedDate.INSTANCE.getDate().toInstant(), ZoneId.systemDefault()); List users = auditableUserRepository.findAll(); for (AuditableUser user : users) { assertThat(user.getFirstname(), is(user.getFirstname().toUpperCase())); - assertThat(user.getLastModifiedBy(), is(thomas)); - assertThat(user.getLastModifiedDate(), is(now)); + assertThat(user.getLastModifiedBy(), is(Optional.of(thomas))); + assertThat(user.getLastModifiedDate(), is(Optional.of(now))); } } } diff --git a/src/test/java/org/springframework/data/jpa/repository/custom/UserCustomExtendedRepository.java b/src/test/java/org/springframework/data/jpa/repository/custom/UserCustomExtendedRepository.java index c883348b8..35b1245dd 100644 --- a/src/test/java/org/springframework/data/jpa/repository/custom/UserCustomExtendedRepository.java +++ b/src/test/java/org/springframework/data/jpa/repository/custom/UserCustomExtendedRepository.java @@ -16,6 +16,7 @@ package org.springframework.data.jpa.repository.custom; import java.util.List; +import java.util.Optional; import org.springframework.data.jpa.domain.sample.User; import org.springframework.transaction.annotation.Transactional; @@ -35,6 +36,6 @@ public interface UserCustomExtendedRepository extends CustomGenericRepository findAll(); @Transactional(readOnly = false, timeout = 10) - User findOne(Integer id); + Optional findOne(Integer id); } \ No newline at end of file diff --git a/src/test/java/org/springframework/data/jpa/repository/query/JpaQueryMethodUnitTests.java b/src/test/java/org/springframework/data/jpa/repository/query/JpaQueryMethodUnitTests.java index 2910abf9c..0892e88f6 100644 --- a/src/test/java/org/springframework/data/jpa/repository/query/JpaQueryMethodUnitTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/query/JpaQueryMethodUnitTests.java @@ -24,6 +24,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; import java.util.List; +import java.util.Optional; import javax.persistence.LockModeType; import javax.persistence.QueryHint; @@ -544,7 +545,7 @@ public class JpaQueryMethodUnitTests { * DATAJPA-689 */ @EntityGraph("User.detail") - User findOne(Long id); + Optional findOne(Long id); /** * DATAJPA-696 diff --git a/src/test/java/org/springframework/data/jpa/repository/query/ParameterBinderUnitTests.java b/src/test/java/org/springframework/data/jpa/repository/query/ParameterBinderUnitTests.java index 85e009c64..482259991 100644 --- a/src/test/java/org/springframework/data/jpa/repository/query/ParameterBinderUnitTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/query/ParameterBinderUnitTests.java @@ -111,14 +111,14 @@ public class ParameterBinderUnitTests { } @Test - public void returnsNullIfNoPageableWasProvided() throws SecurityException, NoSuchMethodException { + public void returnsPageableNoneIfNoPageableWasProvided() throws SecurityException, NoSuchMethodException { Method method = SampleRepository.class.getMethod("validWithPageable", String.class, Pageable.class); JpaParameters parameters = new JpaParameters(method); ParameterBinder binder = new ParameterBinder(parameters, new Object[] { "foo", null }); - assertThat(binder.getPageable(), is(nullValue())); + assertThat(binder.getPageable(), is(Pageable.NONE)); } @Test diff --git a/src/test/java/org/springframework/data/jpa/repository/sample/EmployeeRepositoryWithEmbeddedId.java b/src/test/java/org/springframework/data/jpa/repository/sample/EmployeeRepositoryWithEmbeddedId.java index b9b239515..3a273ad74 100644 --- a/src/test/java/org/springframework/data/jpa/repository/sample/EmployeeRepositoryWithEmbeddedId.java +++ b/src/test/java/org/springframework/data/jpa/repository/sample/EmployeeRepositoryWithEmbeddedId.java @@ -21,7 +21,7 @@ import org.springframework.context.annotation.Lazy; import org.springframework.data.jpa.domain.sample.EmbeddedIdExampleEmployee; import org.springframework.data.jpa.domain.sample.EmbeddedIdExampleEmployeePK; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.Predicate; @@ -35,7 +35,7 @@ import com.querydsl.core.types.Predicate; @Lazy public interface EmployeeRepositoryWithEmbeddedId extends JpaRepository, - QueryDslPredicateExecutor { + QuerydslPredicateExecutor { List findAll(Predicate predicate, OrderSpecifier... orders); diff --git a/src/test/java/org/springframework/data/jpa/repository/sample/EmployeeRepositoryWithIdClass.java b/src/test/java/org/springframework/data/jpa/repository/sample/EmployeeRepositoryWithIdClass.java index 4aff0410b..b2717f988 100644 --- a/src/test/java/org/springframework/data/jpa/repository/sample/EmployeeRepositoryWithIdClass.java +++ b/src/test/java/org/springframework/data/jpa/repository/sample/EmployeeRepositoryWithIdClass.java @@ -21,7 +21,7 @@ import org.springframework.context.annotation.Lazy; import org.springframework.data.jpa.domain.sample.IdClassExampleEmployee; import org.springframework.data.jpa.domain.sample.IdClassExampleEmployeePK; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.Predicate; @@ -34,7 +34,7 @@ import com.querydsl.core.types.Predicate; */ @Lazy public interface EmployeeRepositoryWithIdClass extends JpaRepository, - QueryDslPredicateExecutor { + QuerydslPredicateExecutor { List findAll(Predicate predicate, OrderSpecifier... orders); diff --git a/src/test/java/org/springframework/data/jpa/repository/sample/MailMessageRepository.java b/src/test/java/org/springframework/data/jpa/repository/sample/MailMessageRepository.java index 3fdbd029b..6939c50f8 100644 --- a/src/test/java/org/springframework/data/jpa/repository/sample/MailMessageRepository.java +++ b/src/test/java/org/springframework/data/jpa/repository/sample/MailMessageRepository.java @@ -19,7 +19,7 @@ import java.util.List; import org.springframework.data.jpa.domain.sample.MailMessage; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.Predicate; @@ -28,7 +28,7 @@ import com.querydsl.core.types.Predicate; * @author Thomas Darimont */ public interface MailMessageRepository - extends JpaRepository, QueryDslPredicateExecutor { + extends JpaRepository, QuerydslPredicateExecutor { List findAll(Predicate predicate, OrderSpecifier... orders); } diff --git a/src/test/java/org/springframework/data/jpa/repository/sample/RepositoryMethodsWithEntityGraphConfigRepository.java b/src/test/java/org/springframework/data/jpa/repository/sample/RepositoryMethodsWithEntityGraphConfigRepository.java index 1352bcaad..928ef24be 100644 --- a/src/test/java/org/springframework/data/jpa/repository/sample/RepositoryMethodsWithEntityGraphConfigRepository.java +++ b/src/test/java/org/springframework/data/jpa/repository/sample/RepositoryMethodsWithEntityGraphConfigRepository.java @@ -16,13 +16,14 @@ package org.springframework.data.jpa.repository.sample; import java.util.List; +import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.sample.User; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.CrudRepository; import com.querydsl.core.types.Predicate; @@ -36,7 +37,7 @@ import com.querydsl.core.types.Predicate; * @author Christoph Strobl */ public interface RepositoryMethodsWithEntityGraphConfigRepository - extends CrudRepository, QueryDslPredicateExecutor { + extends CrudRepository, QuerydslPredicateExecutor { /** * Should find all users. @@ -48,7 +49,7 @@ public interface RepositoryMethodsWithEntityGraphConfigRepository * Should fetch all user details */ @EntityGraph(type = EntityGraphType.FETCH, value = "User.detail") - User findOne(Integer id); + Optional findOne(Integer id); // DATAJPA-696 @EntityGraph diff --git a/src/test/java/org/springframework/data/jpa/repository/sample/RoleRepository.java b/src/test/java/org/springframework/data/jpa/repository/sample/RoleRepository.java index bc43203bb..15daa51e0 100644 --- a/src/test/java/org/springframework/data/jpa/repository/sample/RoleRepository.java +++ b/src/test/java/org/springframework/data/jpa/repository/sample/RoleRepository.java @@ -18,10 +18,12 @@ package org.springframework.data.jpa.repository.sample; import javax.persistence.LockModeType; import javax.persistence.QueryHint; +import java.util.Optional; + import org.springframework.data.jpa.domain.sample.Role; import org.springframework.data.jpa.repository.Lock; import org.springframework.data.jpa.repository.QueryHints; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.CrudRepository; import com.querydsl.core.types.Predicate; @@ -32,7 +34,7 @@ import com.querydsl.core.types.Predicate; * @author Oliver Gierke * @author Thomas Darimont */ -public interface RoleRepository extends CrudRepository, QueryDslPredicateExecutor { +public interface RoleRepository extends CrudRepository, QuerydslPredicateExecutor { /* * (non-Javadoc) @@ -48,7 +50,7 @@ public interface RoleRepository extends CrudRepository, QueryDslP */ @Lock(LockModeType.READ) @QueryHints(@QueryHint(name = "foo", value = "bar")) - Role findOne(Integer id); + Optional findOne(Integer id); /* * (non-Javadoc) diff --git a/src/test/java/org/springframework/data/jpa/repository/sample/UserRepository.java b/src/test/java/org/springframework/data/jpa/repository/sample/UserRepository.java index c05497221..322db1049 100644 --- a/src/test/java/org/springframework/data/jpa/repository/sample/UserRepository.java +++ b/src/test/java/org/springframework/data/jpa/repository/sample/UserRepository.java @@ -66,7 +66,7 @@ public interface UserRepository * Redeclaration of {@link CrudRepository#findOne(java.io.Serializable)} to change transaction configuration. */ @Transactional - User findOne(Integer primaryKey); + java.util.Optional findOne(Integer primaryKey); /** * Redeclaration of {@link CrudRepository#delete(java.io.Serializable)}. to make sure the transaction configuration of diff --git a/src/test/java/org/springframework/data/jpa/repository/support/JpaEntityInformationSupportUnitTests.java b/src/test/java/org/springframework/data/jpa/repository/support/JpaEntityInformationSupportUnitTests.java index f92c7ba53..d729242af 100644 --- a/src/test/java/org/springframework/data/jpa/repository/support/JpaEntityInformationSupportUnitTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/support/JpaEntityInformationSupportUnitTests.java @@ -20,6 +20,7 @@ import static org.mockito.Mockito.*; import java.io.Serializable; import java.util.Collections; +import java.util.Optional; import javax.persistence.Entity; import javax.persistence.EntityManager; @@ -82,9 +83,9 @@ public class JpaEntityInformationSupportUnitTests { return null; } - public ID getId(T entity) { + public Optional getId(T entity) { - return null; + return Optional.empty(); } public Class getIdType() { diff --git a/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationIntegrationTests.java b/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationIntegrationTests.java index 4d4fd915a..f19691404 100644 --- a/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationIntegrationTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationIntegrationTests.java @@ -22,6 +22,7 @@ import static org.springframework.data.jpa.repository.support.JpaEntityInformati import java.io.Serializable; import java.sql.Timestamp; import java.util.Date; +import java.util.Optional; import javax.persistence.Access; import javax.persistence.AccessType; @@ -111,8 +112,7 @@ public class JpaMetamodelEntityInformationIntegrationTests { em); Object id = information.getId(entity); - assertThat(id, is(instanceOf(PersistableWithIdClassPK.class))); - assertThat(id, is((Object) new PersistableWithIdClassPK(2L, 4L))); + assertThat(id, is(Optional.of(new PersistableWithIdClassPK(2L, 4L)))); } @Test // DATAJPA-413 @@ -123,8 +123,7 @@ public class JpaMetamodelEntityInformationIntegrationTests { JpaEntityInformation information = getEntityInformation(Item.class, em); Object id = information.getId(item); - assertThat(id, is(instanceOf(ItemId.class))); - assertThat(id, is((Object) new ItemId(2, 1))); + assertThat(id, is(Optional.of(new ItemId(2, 1)))); } @Test // DATAJPA-413 @@ -138,8 +137,7 @@ public class JpaMetamodelEntityInformationIntegrationTests { JpaEntityInformation information = getEntityInformation(ItemSite.class, em); Object id = information.getId(itemSite); - assertThat(id, is(instanceOf(ItemSiteId.class))); - assertThat(id, is((Object) new ItemSiteId(new ItemId(1, 2), 3))); + assertThat(id, is(Optional.of(new ItemSiteId(new ItemId(1, 2), 3)))); } @Test // DATAJPA-413 @@ -153,8 +151,7 @@ public class JpaMetamodelEntityInformationIntegrationTests { JpaEntityInformation information = getEntityInformation(ItemSite.class, em); Object id = information.getId(itemSite); - assertThat(id, is(instanceOf(ItemSiteId.class))); - assertThat(id, is((Object) new ItemSiteId(new ItemId(1, null), 3))); + assertThat(id, is(Optional.of(new ItemSiteId(new ItemId(1, null), 3)))); } @Test // DATAJPA-119 diff --git a/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationUnitTests.java b/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationUnitTests.java index 0147040bc..227339784 100644 --- a/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationUnitTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationUnitTests.java @@ -22,6 +22,7 @@ import static org.mockito.Mockito.*; import java.io.Serializable; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import javax.persistence.metamodel.IdentifiableType; @@ -77,7 +78,7 @@ public class JpaMetamodelEntityInformationUnitTests { PersistableWithIdClass.class, metamodel); PersistableWithIdClass entity = new PersistableWithIdClass(null, null); - assertThat(information.getId(entity), is(nullValue())); + assertThat(information.getId(entity), is(Optional.empty())); entity = new PersistableWithIdClass(2L, null); assertThat(information.getId(entity), is(notNullValue())); diff --git a/src/test/java/org/springframework/data/jpa/repository/support/JpaPersistableEntityInformationUnitTests.java b/src/test/java/org/springframework/data/jpa/repository/support/JpaPersistableEntityInformationUnitTests.java index c4ec425fc..56379b00b 100644 --- a/src/test/java/org/springframework/data/jpa/repository/support/JpaPersistableEntityInformationUnitTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/support/JpaPersistableEntityInformationUnitTests.java @@ -23,6 +23,8 @@ import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import javax.persistence.metamodel.Type; +import java.util.Optional; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -62,11 +64,11 @@ public class JpaPersistableEntityInformationUnitTests { Foo foo = new Foo(); assertThat(entityInformation.isNew(foo), is(false)); - assertThat(entityInformation.getId(foo), is(nullValue())); + assertThat(entityInformation.getId(foo), is(Optional.empty())); foo.id = 1L; assertThat(entityInformation.isNew(foo), is(true)); - assertThat(entityInformation.getId(foo), is(1L)); + assertThat(entityInformation.getId(foo), is(Optional.of(1L))); } @SuppressWarnings("serial") diff --git a/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryBeanUnitTests.java b/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryBeanUnitTests.java index e909b4fab..728f84d65 100644 --- a/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryBeanUnitTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryBeanUnitTests.java @@ -22,6 +22,7 @@ import static org.mockito.Mockito.*; import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.metamodel.Metamodel; @@ -30,6 +31,8 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.ListableBeanFactory; @@ -37,6 +40,9 @@ import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.data.domain.Persistable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.Repository; +import org.springframework.data.repository.core.EntityInformation; +import org.springframework.data.repository.core.RepositoryInformation; +import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.RepositoryFactorySupport; /** @@ -52,7 +58,7 @@ public class JpaRepositoryFactoryBeanUnitTests { JpaRepositoryFactoryBean factoryBean; @Mock EntityManager entityManager; - @Mock RepositoryFactorySupport factory; + StubRepositoryFactorySupport factory; @Mock ListableBeanFactory beanFactory; @Mock PersistenceExceptionTranslator translator; @Mock Repository repository; @@ -66,9 +72,10 @@ public class JpaRepositoryFactoryBeanUnitTests { beans.put("foo", translator); when(beanFactory.getBeansOfType(eq(PersistenceExceptionTranslator.class), anyBoolean(), anyBoolean())) .thenReturn(beans); - when(factory.getRepository(any(Class.class), any(Object.class))).thenReturn(repository); when(entityManager.getMetamodel()).thenReturn(metamodel); + factory = Mockito.spy(new StubRepositoryFactorySupport(repository)); + // Setup standard factory configuration factoryBean = new DummyJpaRepositoryFactoryBean( SimpleSampleRepository.class); @@ -126,7 +133,7 @@ public class JpaRepositoryFactoryBeanUnitTests { } /** - * Helper class to make the factory use {@link PersistableMetadata} . + * Helper class to make the factory use {@link Persistable} . * * @author Oliver Gierke */ @@ -134,4 +141,37 @@ public class JpaRepositoryFactoryBeanUnitTests { private static abstract class User implements Persistable { } + + /** + * required to trick Mockito on invoking protected getRepository(Class repositoryInterface, Optional + * customImplementation + */ + private static class StubRepositoryFactorySupport extends RepositoryFactorySupport { + + private final Repository repository; + + private StubRepositoryFactorySupport(Repository repository) { + this.repository = repository; + } + + @Override + protected T getRepository(Class repositoryInterface, Optional customImplementation) { + return (T) repository; + } + + @Override + public EntityInformation getEntityInformation(Class domainClass) { + return null; + } + + @Override + protected Object getTargetRepository(RepositoryInformation metadata) { + return null; + } + + @Override + protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { + return null; + } + } } diff --git a/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryUnitTests.java b/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryUnitTests.java index b614c5503..875a4140f 100644 --- a/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryUnitTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryUnitTests.java @@ -21,6 +21,7 @@ import static org.mockito.Mockito.*; import java.io.IOException; import java.io.Serializable; +import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -37,7 +38,7 @@ import org.springframework.data.jpa.domain.sample.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.custom.CustomGenericJpaRepositoryFactory; import org.springframework.data.jpa.repository.custom.UserCustomExtendedRepository; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.core.support.DefaultRepositoryMetadata; import org.springframework.data.repository.query.QueryLookupStrategy.Key; import org.springframework.test.util.ReflectionTestUtils; @@ -147,12 +148,12 @@ public class JpaRepositoryFactoryUnitTests { public void usesQueryDslRepositoryIfInterfaceImplementsExecutor() { when(entityInformation.getJavaType()).thenReturn(User.class); - assertEquals(QueryDslJpaRepository.class, + assertEquals(QuerydslJpaRepository.class, factory.getRepositoryBaseClass(new DefaultRepositoryMetadata(QueryDslSampleRepository.class))); try { QueryDslSampleRepository repository = factory.getRepository(QueryDslSampleRepository.class); - assertEquals(QueryDslJpaRepository.class, ((Advised) repository).getTargetClass()); + assertEquals(QuerydslJpaRepository.class, ((Advised) repository).getTargetClass()); } catch (IllegalArgumentException e) { assertThat(e.getStackTrace()[0].getClassName(), is("org.springframework.data.querydsl.SimpleEntityPathResolver")); } @@ -181,7 +182,7 @@ public class JpaRepositoryFactoryUnitTests { private interface SimpleSampleRepository extends JpaRepository { @Transactional - User findOne(Integer id); + Optional findOne(Integer id); } /** @@ -218,7 +219,7 @@ public class JpaRepositoryFactoryUnitTests { } - private interface QueryDslSampleRepository extends SimpleSampleRepository, QueryDslPredicateExecutor { + private interface QueryDslSampleRepository extends SimpleSampleRepository, QuerydslPredicateExecutor { } diff --git a/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryTests.java b/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryTests.java index aafbdccaf..0a1931b95 100644 --- a/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryTests.java @@ -19,6 +19,7 @@ import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.util.Arrays; +import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @@ -66,7 +67,7 @@ public class JpaRepositoryTests { repository.saveAndFlush(entity); assertThat(repository.exists(new SampleEntityPK("foo", "bar")), is(true)); assertThat(repository.count(), is(1L)); - assertThat(repository.findOne(new SampleEntityPK("foo", "bar")), is(entity)); + assertThat(repository.findOne(new SampleEntityPK("foo", "bar")), is(Optional.of(entity))); repository.delete(Arrays.asList(entity)); repository.flush(); @@ -84,7 +85,7 @@ public class JpaRepositoryTests { PersistableWithIdClassPK id = new PersistableWithIdClassPK(entity.getFirst(), entity.getSecond()); - assertThat(idClassRepository.findOne(id), is(entity)); + assertThat(idClassRepository.findOne(id), is(Optional.of(entity))); } @Test // DATAJPA-266 diff --git a/src/test/java/org/springframework/data/jpa/repository/support/QueryDslJpaRepositoryTests.java b/src/test/java/org/springframework/data/jpa/repository/support/QueryDslJpaRepositoryTests.java index b8188b135..ed264bbaa 100644 --- a/src/test/java/org/springframework/data/jpa/repository/support/QueryDslJpaRepositoryTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/support/QueryDslJpaRepositoryTests.java @@ -49,7 +49,7 @@ import com.querydsl.core.types.dsl.PathBuilder; import com.querydsl.core.types.dsl.PathBuilderFactory; /** - * Integration test for {@link QueryDslJpaRepository}. + * Integration test for {@link QuerydslJpaRepository}. * * @author Oliver Gierke * @author Thomas Darimont @@ -62,7 +62,7 @@ public class QueryDslJpaRepositoryTests { @PersistenceContext EntityManager em; - QueryDslJpaRepository repository; + QuerydslJpaRepository repository; QUser user = new QUser("user"); User dave, carter, oliver; Role adminRole; @@ -73,7 +73,7 @@ public class QueryDslJpaRepositoryTests { JpaEntityInformation information = new JpaMetamodelEntityInformation(User.class, em.getMetamodel()); - repository = new QueryDslJpaRepository(information, em); + repository = new QuerydslJpaRepository(information, em); dave = repository.save(new User("Dave", "Matthews", "dave@matthews.com")); carter = repository.save(new User("Carter", "Beauford", "carter@beauford.com")); oliver = repository.save(new User("Oliver", "matthews", "oliver@matthews.com")); diff --git a/src/test/resources/config/namespace-customfactory-context.xml b/src/test/resources/config/namespace-customfactory-context.xml index e621ee2cb..f10632a5b 100644 --- a/src/test/resources/config/namespace-customfactory-context.xml +++ b/src/test/resources/config/namespace-customfactory-context.xml @@ -9,7 +9,6 @@ - + \ No newline at end of file