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.
This commit is contained in:
Christoph Strobl
2017-02-13 15:01:50 +01:00
committed by Oliver Gierke
parent a04d9b868b
commit 6ab6050690
54 changed files with 342 additions and 249 deletions

View File

@@ -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 <U> the auditing type. Typically some kind of user.
* @param <PK> the type of the auditing type's idenifier
*/
@MappedSuperclass
public abstract class AbstractAuditable<U, PK extends Serializable> extends AbstractPersistable<PK> implements
Auditable<U, PK> {
Auditable<U, PK, LocalDateTime> {
private static final long serialVersionUID = 141481953116476081L;
@@ -56,9 +59,9 @@ public abstract class AbstractAuditable<U, PK extends Serializable> extends Abst
*
* @see org.springframework.data.domain.Auditable#getCreatedBy()
*/
public U getCreatedBy() {
public Optional<U> getCreatedBy() {
return createdBy;
return Optional.ofNullable(createdBy);
}
/*
@@ -67,9 +70,9 @@ public abstract class AbstractAuditable<U, PK extends Serializable> extends Abst
* @see
* org.springframework.data.domain.Auditable#setCreatedBy(java.lang.Object)
*/
public void setCreatedBy(final U createdBy) {
public void setCreatedBy(final Optional<? extends U> createdBy) {
this.createdBy = createdBy;
this.createdBy = createdBy.orElse(null);
}
/*
@@ -77,9 +80,10 @@ public abstract class AbstractAuditable<U, PK extends Serializable> extends Abst
*
* @see org.springframework.data.domain.Auditable#getCreatedDate()
*/
public DateTime getCreatedDate() {
@Override
public Optional<LocalDateTime> 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<U, PK extends Serializable> extends Abst
* org.springframework.data.domain.Auditable#setCreatedDate(org.joda.time
* .DateTime)
*/
public void setCreatedDate(final DateTime createdDate) {
public void setCreatedDate(Optional<? extends LocalDateTime> 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<U, PK extends Serializable> extends Abst
*
* @see org.springframework.data.domain.Auditable#getLastModifiedBy()
*/
public U getLastModifiedBy() {
public Optional<U> getLastModifiedBy() {
return lastModifiedBy;
return Optional.ofNullable(lastModifiedBy);
}
/*
@@ -111,9 +115,9 @@ public abstract class AbstractAuditable<U, PK extends Serializable> extends Abst
* org.springframework.data.domain.Auditable#setLastModifiedBy(java.lang
* .Object)
*/
public void setLastModifiedBy(final U lastModifiedBy) {
public void setLastModifiedBy(final Optional<? extends U> lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
this.lastModifiedBy = lastModifiedBy.orElse(null);
}
/*
@@ -121,9 +125,9 @@ public abstract class AbstractAuditable<U, PK extends Serializable> extends Abst
*
* @see org.springframework.data.domain.Auditable#getLastModifiedDate()
*/
public DateTime getLastModifiedDate() {
public Optional<LocalDateTime> 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<U, PK extends Serializable> extends Abst
* org.springframework.data.domain.Auditable#setLastModifiedDate(org.joda
* .time.DateTime)
*/
public void setLastModifiedDate(final DateTime lastModifiedDate) {
public void setLastModifiedDate(Optional<? extends LocalDateTime> lastModifiedDate) {
this.lastModifiedDate = null == lastModifiedDate ? null : lastModifiedDate.toDate();
this.lastModifiedDate = lastModifiedDate.map(d -> Date.from(d.atZone(ZoneId.systemDefault()).toInstant())).orElse(null);
}
}

View File

@@ -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));
}
}
}

View File

@@ -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);
}
/*

View File

@@ -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<T> extends BasicPersistentEntity<T, JpaPersistentProperty>
@@ -49,7 +51,7 @@ class JpaPersistentEntityImpl<T> extends BasicPersistentEntity<T, JpaPersistentP
*/
public JpaPersistentEntityImpl(TypeInformation<T> 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<T> extends BasicPersistentEntity<T, JpaPersistentP
super.verify();
JpaPersistentProperty versionProperty = getVersionProperty();
Optional<JpaPersistentProperty> 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<T> extends BasicPersistentEntity<T, JpaPersistentP
* @see org.springframework.data.mapping.IdentifierAccessor#getIdentifier()
*/
@Override
public Object getIdentifier() {
return proxyIdAccessor.shouldUseAccessorFor(bean) ? proxyIdAccessor.getIdentifierFrom(bean)
public Optional<Object> getIdentifier() {
return proxyIdAccessor.shouldUseAccessorFor(bean) ? Optional.ofNullable(proxyIdAccessor.getIdentifierFrom(bean))
: super.getIdentifier();
}
}

View File

@@ -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<JpaPersistentProperty>
@@ -97,15 +100,14 @@ class JpaPersistentPropertyImpl extends AnnotationBasedPersistentProperty<JpaPer
* Creates a new {@link JpaPersistentPropertyImpl}
*
* @param metamodel must not be {@literal null}.
* @param field must not be {@literal null}.
* @param propertyDescriptor can be {@literal null}.
* @param property must not be {@literal null}.
* @param owner must not be {@literal null}.
* @param simpleTypeHolder must not be {@literal null}.
*/
public JpaPersistentPropertyImpl(Metamodel metamodel, Field field, PropertyDescriptor propertyDescriptor,
public JpaPersistentPropertyImpl(Metamodel metamodel, Property property,
PersistentEntity<?, JpaPersistentProperty> 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<JpaPer
*/
private Boolean detectPropertyAccess() {
org.springframework.data.annotation.AccessType accessType = findAnnotation(
Optional<org.springframework.data.annotation.AccessType> 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> 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<JpaPer
for (Class<? extends Annotation> associationAnnotation : ASSOCIATION_ANNOTATIONS) {
Annotation annotation = findAnnotation(associationAnnotation);
Object targetEntity = AnnotationUtils.getValue(annotation, "targetEntity");
Optional<? extends Annotation> 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<JpaPer
for (Class<? extends Annotation> annotationType : UPDATEABLE_ANNOTATIONS) {
Annotation annotation = findAnnotation(annotationType);
Optional<? extends Annotation> 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;
}
}

View File

@@ -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 <T> The type of the repository.
*/
class JpaRepositoryBean<T> extends CdiRepositoryBean<T> {
@@ -50,7 +52,7 @@ class JpaRepositoryBean<T> extends CdiRepositoryBean<T> {
* @param detector can be {@literal null}.
*/
JpaRepositoryBean(BeanManager beanManager, Bean<EntityManager> entityManagerBean, Set<Annotation> qualifiers,
Class<T> repositoryType, CustomRepositoryImplementationDetector detector) {
Class<T> repositoryType, Optional<CustomRepositoryImplementationDetector> detector) {
super(qualifiers, repositoryType, beanManager, detector);
@@ -63,13 +65,13 @@ class JpaRepositoryBean<T> extends CdiRepositoryBean<T> {
* @see org.springframework.data.repository.cdi.CdiRepositoryBean#create(javax.enterprise.context.spi.CreationalContext, java.lang.Class, java.lang.Object)
*/
@Override
public T create(CreationalContext<T> creationalContext, Class<T> repositoryType, Object customImplementation) {
public T create(CreationalContext<T> creationalContext, Class<T> repositoryType, Optional<Object> 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);
}
}

View File

@@ -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<T>(beanManager, entityManagerBean, qualifiers, repositoryType,
getCustomImplementationDetector());
Optional.ofNullable(getCustomImplementationDetector()));
}
}

View File

@@ -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<String> 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<String> 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<String> entityManagerFactoryRef = config == null ? Optional.empty()
: config.getAttribute("entityManagerFactoryRef");
return entityManagerFactoryRef.orElse("entityManagerFactory");
}
}

View File

@@ -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()));
}

View File

@@ -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

View File

@@ -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));

View File

@@ -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;

View File

@@ -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<T> reifiedType = Expression.class.equals(type) ? (Class<T>) Object.class : type;
ParameterExpression<T> 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<T> value = new ParameterMetadata<T>(expression, part.getType(),
bindableParameterValues == null ? ParameterMetadata.PLACEHOLDER : bindableParameterValues.next(),
this.persistenceProvider);

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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 {

View File

@@ -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<T, ID extends Serializable> extends J
* @see org.springframework.data.repository.core.EntityInformation#getId(java.lang.Object)
*/
@SuppressWarnings("unchecked")
public ID getId(T entity) {
public Optional<ID> 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<T, ID extends Serializable> 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<T, ID extends Serializable> 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) {

View File

@@ -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<T extends Persistable<ID>, ID extends Serializable> extends
JpaMetamodelEntityInformation<T, ID> {
@@ -53,7 +55,7 @@ public class JpaPersistableEntityInformation<T extends Persistable<ID>, 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<ID> getId(T entity) {
return Optional.ofNullable(entity.getId());
}
}

View File

@@ -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 <T>
* @param <ID>
* @param entityManager
* @see #getTargetRepository(RepositoryMetadata)
* @return
*/
protected <T, ID extends Serializable> 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<QueryLookupStrategy> getQueryLookupStrategy(Key key, EvaluationContextProvider evaluationContextProvider) {
return Optional.of(JpaQueryLookupStrategy.create(entityManager, key, extractor, evaluationContextProvider));
}
/*

View File

@@ -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 <T> JPQLQuery<T> applyPagination(Pageable pageable, JPQLQuery<T> query) {
if (pageable == null) {
if (pageable == null || ObjectUtils.nullSafeEquals(Pageable.NONE, pageable)) {
return query;
}

View File

@@ -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<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
implements QueryDslPredicateExecutor<T> {
public class QuerydslJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
implements QuerydslPredicateExecutor<T> {
private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;
@@ -58,26 +58,26 @@ public class QueryDslJpaRepository<T, ID extends Serializable> 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<T, ID> entityInformation, EntityManager entityManager) {
public QuerydslJpaRepository(JpaEntityInformation<T, ID> 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<T, ID> entityInformation, EntityManager entityManager,
EntityPathResolver resolver) {
public QuerydslJpaRepository(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager,
EntityPathResolver resolver) {
super(entityInformation, entityManager);
@@ -141,13 +141,7 @@ public class QueryDslJpaRepository<T, ID extends Serializable> extends SimpleJpa
final JPQLQuery<?> countQuery = createCountQuery(predicate);
JPQLQuery<T> 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());
}
/*

View File

@@ -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 <T> the type of the entity to handle
* @param <ID> the type of the entity's identifier
*/
@@ -147,14 +149,8 @@ public class SimpleJpaRepository<T, ID extends Serializable>
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<T, ID extends Serializable>
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
*/
public T findOne(ID id) {
public Optional<T> findOne(ID id) {
Assert.notNull(id, ID_MUST_NOT_BE_NULL);
Class<T> domainType = getDomainClass();
if (metadata == null) {
return em.find(domainType, id);
return Optional.ofNullable(em.find(domainType, id));
}
LockModeType type = metadata.getLockModeType();
Map<String, Object> 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<T, ID extends Serializable>
List<T> results = new ArrayList<T>();
for (ID id : ids) {
results.add(findOne(id));
findOne(id).ifPresent(results::add);
}
return results;
@@ -583,16 +579,14 @@ public class SimpleJpaRepository<T, ID extends Serializable>
protected <S extends T> Page<S> readPage(TypedQuery<S> query, final Class<S> domainClass, Pageable pageable,
final Specification<S> 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<T, ID extends Serializable>
Root<S> 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));
}

View File

@@ -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;

View File

@@ -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<AuditableUser> {
*
* @see org.springframework.data.domain.AuditorAware#getCurrentAuditor()
*/
public AuditableUser getCurrentAuditor() {
public Optional<AuditableUser> getCurrentAuditor() {
return auditor;
return Optional.ofNullable(auditor);
}
}

View File

@@ -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<?, ?, LocalDateTime> 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<AuditableUser, ?> auditable) {
private static void assertUserIsAuditor(AuditableUser user, Auditable<AuditableUser, ?, LocalDateTime> 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)));
}
}

View File

@@ -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));

View File

@@ -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 {

View File

@@ -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));

View File

@@ -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));
}

View File

@@ -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));
}

View File

@@ -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"),

View File

@@ -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<IdClassExampleEmployee> result = employeeRepositoryWithIdClass.findAll(Arrays.asList(emp1PK, emp2PK));

View File

@@ -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<ItemSite> loaded = itemSiteRepository
.findOne(new ItemSiteId(new ItemId(item.getId(), item.getManufacturerId()), site.getId()));
assertThat(loaded, is(notNullValue()));
assertThat(loaded.isPresent(), is(true));
}
}

View File

@@ -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

View File

@@ -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<User> colleagues = reference.getColleagues();
assertThat(colleagues, is(notNullValue()));

View File

@@ -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<AuditableUser> 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)));
}
}
}

View File

@@ -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<Us
List<User> findAll();
@Transactional(readOnly = false, timeout = 10)
User findOne(Integer id);
Optional<User> findOne(Integer id);
}

View File

@@ -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<User> findOne(Long id);
/**
* DATAJPA-696

View File

@@ -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

View File

@@ -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<EmbeddedIdExampleEmployee, EmbeddedIdExampleEmployeePK>,
QueryDslPredicateExecutor<EmbeddedIdExampleEmployee> {
QuerydslPredicateExecutor<EmbeddedIdExampleEmployee> {
List<EmbeddedIdExampleEmployee> findAll(Predicate predicate, OrderSpecifier<?>... orders);

View File

@@ -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<IdClassExampleEmployee, IdClassExampleEmployeePK>,
QueryDslPredicateExecutor<IdClassExampleEmployee> {
QuerydslPredicateExecutor<IdClassExampleEmployee> {
List<IdClassExampleEmployee> findAll(Predicate predicate, OrderSpecifier<?>... orders);

View File

@@ -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<MailMessage, Long>, QueryDslPredicateExecutor<MailMessage> {
extends JpaRepository<MailMessage, Long>, QuerydslPredicateExecutor<MailMessage> {
List<MailMessage> findAll(Predicate predicate, OrderSpecifier<?>... orders);
}

View File

@@ -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<User, Integer>, QueryDslPredicateExecutor<User> {
extends CrudRepository<User, Integer>, QuerydslPredicateExecutor<User> {
/**
* 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<User> findOne(Integer id);
// DATAJPA-696
@EntityGraph

View File

@@ -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<Role, Integer>, QueryDslPredicateExecutor<Role> {
public interface RoleRepository extends CrudRepository<Role, Integer>, QuerydslPredicateExecutor<Role> {
/*
* (non-Javadoc)
@@ -48,7 +50,7 @@ public interface RoleRepository extends CrudRepository<Role, Integer>, QueryDslP
*/
@Lock(LockModeType.READ)
@QueryHints(@QueryHint(name = "foo", value = "bar"))
Role findOne(Integer id);
Optional<Role> findOne(Integer id);
/*
* (non-Javadoc)

View File

@@ -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<User> findOne(Integer primaryKey);
/**
* Redeclaration of {@link CrudRepository#delete(java.io.Serializable)}. to make sure the transaction configuration of

View File

@@ -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<ID> getId(T entity) {
return null;
return Optional.empty();
}
public Class<ID> getIdType() {

View File

@@ -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<Item, ?> 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<ItemSite, ?> 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<ItemSite, ?> 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

View File

@@ -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()));

View File

@@ -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")

View File

@@ -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<SimpleSampleRepository, User, Integer> 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, User, Integer>(
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<Long> {
}
/**
* required to trick Mockito on invoking protected getRepository(Class<T> repositoryInterface, Optional<Object>
* customImplementation
*/
private static class StubRepositoryFactorySupport extends RepositoryFactorySupport {
private final Repository<?, ?> repository;
private StubRepositoryFactorySupport(Repository<?, ?> repository) {
this.repository = repository;
}
@Override
protected <T> T getRepository(Class<T> repositoryInterface, Optional<Object> customImplementation) {
return (T) repository;
}
@Override
public <T, ID extends Serializable> EntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return null;
}
@Override
protected Object getTargetRepository(RepositoryInformation metadata) {
return null;
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return null;
}
}
}

View File

@@ -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<User, Integer> {
@Transactional
User findOne(Integer id);
Optional<User> findOne(Integer id);
}
/**
@@ -218,7 +219,7 @@ public class JpaRepositoryFactoryUnitTests {
}
private interface QueryDslSampleRepository extends SimpleSampleRepository, QueryDslPredicateExecutor<User> {
private interface QueryDslSampleRepository extends SimpleSampleRepository, QuerydslPredicateExecutor<User> {
}

View File

@@ -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

View File

@@ -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<User, Integer> repository;
QuerydslJpaRepository<User, Integer> repository;
QUser user = new QUser("user");
User dave, carter, oliver;
Role adminRole;
@@ -73,7 +73,7 @@ public class QueryDslJpaRepositoryTests {
JpaEntityInformation<User, Integer> information = new JpaMetamodelEntityInformation<User, Integer>(User.class,
em.getMetamodel());
repository = new QueryDslJpaRepository<User, Integer>(information, em);
repository = new QuerydslJpaRepository<User, Integer>(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"));

View File

@@ -9,7 +9,6 @@
<import resource="../infrastructure.xml" />
<import resource="../tx-manager.xml" />
<jpa:repositories base-package="org.springframework.**.repository.custom"
factory-class="org.springframework.data.jpa.repository.custom.CustomGenericJpaRepositoryFactoryBean" />
<jpa:repositories base-package="org.springframework.**.repository.custom" base-class="org.springframework.data.jpa.repository.custom.CustomGenericJpaRepository" />
</beans>