Switch MongoDB samples to records.

See #606.
This commit is contained in:
Mark Paluch
2021-04-28 15:18:59 +02:00
parent b44dc3dea1
commit e565f33872
69 changed files with 395 additions and 555 deletions

View File

@@ -21,7 +21,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
/**
* Test configuration to connect to a MongoDB named "test" using a {@code MongoClient}. <br />
* Also enables Spring Data repositories for MongoDB.
@@ -44,11 +43,29 @@ class ApplicationConfiguration {
return (immutablePerson, collection) -> {
int randomNumber = ThreadLocalRandom.current().nextInt(1, 100);
var randomNumber = ThreadLocalRandom.current().nextInt(1, 100);
// withRandomNumber is a so called wither method returning a new instance of the entity with a new value assigned
return immutablePerson.withRandomNumber(randomNumber);
};
}
/**
* Register the {@link BeforeConvertCallback} used to update an {@link ImmutableRecord} before handing over the newly
* created instance to the actual mapping layer performing the conversion into the store native
* {@link org.bson.Document} representation.
*
* @return a {@link BeforeConvertCallback} for {@link ImmutablePerson}.
*/
@Bean
BeforeConvertCallback<ImmutableRecord> beforeRecordConvertCallback() {
return (rec, collection) -> {
var randomNumber = ThreadLocalRandom.current().nextInt(1, 100);
return new ImmutableRecord(rec.id(), randomNumber);
};
}
}

View File

@@ -17,7 +17,7 @@ package example.springdata.mongodb.immutable;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Wither;
import lombok.With;
import org.bson.types.ObjectId;
@@ -26,7 +26,7 @@ import org.bson.types.ObjectId;
*
* @author Mark Paluch
*/
@Wither
@With
@Getter
@RequiredArgsConstructor
public class ImmutablePerson {

View File

@@ -0,0 +1,21 @@
/*
* Copyright 2021 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.immutable;
import org.bson.types.ObjectId;
record ImmutableRecord(ObjectId id, int randomNumber) {
}

View File

@@ -15,15 +15,11 @@
*/
package example.springdata.mongodb.projections;
import lombok.Value;
/**
* A sample DTO only containing the firstname.
*
* @author Oliver Gierke
*/
@Value
class CustomerDto {
record CustomerDto(String firstname) {
String firstname;
}

View File

@@ -15,40 +15,12 @@
*/
package example.springdata.mongodb.unwrapping;
import java.util.Objects;
/**
* Value object capturing the {@code email} address.
*
* @author Christoph Strobl
*/
public class Email { // might as well be a record type in more recent java versions
private final String email;
public Email(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return email;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Email email1 = (Email) o;
return Objects.equals(email, email1.email);
}
@Override
public int hashCode() {
return Objects.hash(email);
}
public record Email(String email) {
}

View File

@@ -83,7 +83,7 @@ public class User {
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
var user = (User) o;
return Objects.equals(id, user.id) &&
Objects.equals(userName, user.userName) &&
Objects.equals(email, user.email);

View File

@@ -38,7 +38,7 @@ public class UserName { // might as well be a record type in more recent java ve
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserName userName = (UserName) o;
var userName = (UserName) o;
return Objects.equals(username, userName.username);
}

View File

@@ -71,12 +71,12 @@ public class AdvancedIntegrationTests {
// execute another finder without meta attributes that should not be picked up
repository.findByLastname(dave.getLastname(), Sort.by("firstname"));
FindIterable<Document> cursor = operations.getCollection(ApplicationConfiguration.SYSTEM_PROFILE_DB)
var cursor = operations.getCollection(ApplicationConfiguration.SYSTEM_PROFILE_DB)
.find(new BasicDBObject("query.$comment", AdvancedRepository.META_COMMENT));
for (Document document : cursor) {
for (var document : cursor) {
Document query = (Document) document.get("query");
var query = (Document) document.get("query");
assertThat(query).containsKey("foo");
}
}

View File

@@ -76,7 +76,7 @@ public class ServersideScriptTests {
@Ignore
public void complexScriptExecutionSimulatingPutIfAbsent() {
Customer ned = new Customer("Ned", "Stark");
var ned = new Customer("Ned", "Stark");
ned.setId("ned-stark");
// #1: on first insert null has to be returned
@@ -94,14 +94,14 @@ public class ServersideScriptTests {
private ExecutableMongoScript createExecutablePutIfAbsentScript(Customer customer) {
String collectionName = operations.getCollectionName(Customer.class);
Object id = operations.getConverter().getMappingContext().getRequiredPersistentEntity(Customer.class)
var collectionName = operations.getCollectionName(Customer.class);
var id = operations.getConverter().getMappingContext().getRequiredPersistentEntity(Customer.class)
.getIdentifierAccessor(customer).getIdentifier();
Document document = new Document();
var document = new Document();
operations.getConverter().write(customer, document);
String scriptString = String.format(
var scriptString = String.format(
"object = db.%1$s.findOne({\"_id\": \"%2$s\"}); if (object == null) { db.%1s.insert(%3$s); return null; } else { return object; }",
collectionName, id, document);

View File

@@ -65,7 +65,7 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void setsIdOnSave() {
Customer dave = repository.save(new Customer("Dave", "Matthews"));
var dave = repository.save(new Customer("Dave", "Matthews"));
assertThat(dave.getId(), is(notNullValue()));
}
@@ -75,8 +75,8 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void findCustomersUsingQuerydslSort() {
QCustomer customer = QCustomer.customer;
List<Customer> result = repository.findByLastname("Matthews", new QSort(customer.firstname.asc()));
var customer = QCustomer.customer;
var result = repository.findByLastname("Matthews", new QSort(customer.firstname.asc()));
assertThat(result, hasSize(2));
assertThat(result.get(0), is(dave));
@@ -89,7 +89,7 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void findCustomersAsStream() {
try (Stream<Customer> result = repository.findAllByCustomQueryWithStream()) {
try (var result = repository.findAllByCustomQueryWithStream()) {
result.forEach(System.out::println);
}
}
@@ -100,24 +100,24 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void exposesGeoSpatialFunctionality() {
GeospatialIndex indexDefinition = new GeospatialIndex("address.location");
var indexDefinition = new GeospatialIndex("address.location");
indexDefinition.getIndexOptions().put("min", -180);
indexDefinition.getIndexOptions().put("max", 180);
operations.indexOps(Customer.class).ensureIndex(indexDefinition);
Customer ollie = new Customer("Oliver", "Gierke");
var ollie = new Customer("Oliver", "Gierke");
ollie.setAddress(new Address(new Point(52.52548, 13.41477)));
ollie = repository.save(ollie);
Point referenceLocation = new Point(52.51790, 13.41239);
Distance oneKilometer = new Distance(1, Metrics.KILOMETERS);
var referenceLocation = new Point(52.51790, 13.41239);
var oneKilometer = new Distance(1, Metrics.KILOMETERS);
GeoResults<Customer> result = repository.findByAddressLocationNear(referenceLocation, oneKilometer);
var result = repository.findByAddressLocationNear(referenceLocation, oneKilometer);
assertThat(result.getContent(), hasSize(1));
Distance distanceToFirstStore = result.getContent().get(0).getDistance();
var distanceToFirstStore = result.getContent().get(0).getDistance();
assertThat(distanceToFirstStore.getMetric(), is(Metrics.KILOMETERS));
assertThat(distanceToFirstStore.getValue(), closeTo(0.862, 0.001));
}

View File

@@ -17,6 +17,7 @@ package example.springdata.mongodb.immutable;
import static org.assertj.core.api.Assertions.*;
import org.bson.types.ObjectId;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -49,12 +50,29 @@ public class ImmutableEntityIntegrationTest {
@Test
public void setsRandomNumberOnSave() {
ImmutablePerson unsaved = new ImmutablePerson();
var unsaved = new ImmutablePerson();
assertThat(unsaved.getRandomNumber()).isZero();
ImmutablePerson saved = operations.save(unsaved);
var saved = operations.save(unsaved);
assertThat(saved.getId()).isNotNull();
assertThat(saved.getRandomNumber()).isNotZero();
}
/**
* Test case to show that automatically generated ids are assigned to the immutable domain object and how the
* {@link ImmutableRecord#getRandomNumber()} gets set via {@link ApplicationConfiguration#beforeConvertCallback()}.
*/
@Test
public void setsRandomNumberOnSaveRecord() {
var unsaved = new ImmutableRecord(null, 0);
assertThat(unsaved.randomNumber()).isZero();
var saved = operations.save(unsaved);
assertThat(saved.id()).isNotNull();
assertThat(saved.randomNumber()).isNotZero();
}
}

View File

@@ -63,7 +63,7 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void projectsEntityIntoInterface() {
Collection<CustomerProjection> result = customers.findAllProjectedBy();
var result = customers.findAllProjectedBy();
assertThat(result, hasSize(2));
assertThat(result.iterator().next().getFirstname(), is("Dave"));
@@ -72,16 +72,16 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void projectsToDto() {
Collection<CustomerDto> result = customers.findAllDtoedBy();
var result = customers.findAllDtoedBy();
assertThat(result, hasSize(2));
assertThat(result.iterator().next().getFirstname(), is("Dave"));
assertThat(result.iterator().next().firstname(), is("Dave"));
}
@Test
public void projectsDynamically() {
Collection<CustomerProjection> result = customers.findByFirstname("Dave", CustomerProjection.class);
var result = customers.findByFirstname("Dave", CustomerProjection.class);
assertThat(result, hasSize(1));
assertThat(result.iterator().next().getFirstname(), is("Dave"));
@@ -90,7 +90,7 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void projectsIndividualDynamically() {
CustomerSummary result = customers.findProjectedById(dave.getId(), CustomerSummary.class);
var result = customers.findProjectedById(dave.getId(), CustomerSummary.class);
assertThat(result, is(notNullValue()));
assertThat(result.getFullName(), is("Dave Matthews"));
@@ -102,7 +102,7 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void projectIndividualInstance() {
CustomerProjection result = customers.findProjectedById(dave.getId());
var result = customers.findProjectedById(dave.getId());
assertThat(result, is(notNullValue()));
assertThat(result.getFirstname(), is("Dave"));
@@ -112,7 +112,7 @@ public class CustomerRepositoryIntegrationTest {
@Test
public void supportsProjectionInCombinationWithPagination() {
Page<CustomerProjection> page = customers
var page = customers
.findPagedProjectedBy(PageRequest.of(0, 1, Sort.by(Direction.ASC, "lastname")));
assertThat(page.getContent().get(0).getFirstname(), is("Carter"));

View File

@@ -53,13 +53,13 @@ class UnwrappingIntegrationTests {
@Test
void documentStructure() {
org.bson.Document stored = operations.execute(User.class, collection -> {
var stored = operations.execute(User.class, collection -> {
return collection.find(Filters.eq("_id", rogelio.getId())).first();
});
assertThat(stored).containsAllEntriesOf(new Document("_id", rogelio.getId())
.append("username", rogelio.getUserName().getUsername())
.append("primary_email", rogelio.getEmail().getEmail())
.append("primary_email", rogelio.getEmail().email())
);
}
@@ -77,6 +77,6 @@ class UnwrappingIntegrationTests {
*/
@Test
void queryViaPropertyOfValueType() {
assertThat(repository.findByEmailEmail(jane.getEmail().getEmail())).isEqualTo(jane);
assertThat(repository.findByEmailEmail(jane.getEmail().email())).isEqualTo(jane);
}
}