Example with adding indexes from code and like annotation.

This commit is contained in:
coach88 2015-08-13 14:11:37 +03:00
parent 4e02612c1c
commit 13cf53aaf4
2 changed files with 47 additions and 0 deletions

View File

@ -1,7 +1,12 @@
package org.baeldung.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import com.mysema.query.annotations.QueryEntity;
@ -13,6 +18,10 @@ public class User {
private String id;
private String name;
private Integer age;
@DBRef
@Indexed
@Field("email")
private EmailAddress emailAddress;
public String getId() {
return id;
@ -37,4 +46,12 @@ public class User {
public void setAge(final Integer age) {
this.age = age;
}
public EmailAddress getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(EmailAddress emailAddress) {
this.emailAddress = emailAddress;
}
}

View File

@ -6,6 +6,7 @@ import static org.junit.Assert.assertThat;
import java.util.List;
import org.baeldung.config.MongoConfig;
import org.baeldung.model.EmailAddress;
import org.baeldung.model.User;
import org.junit.After;
import org.junit.Before;
@ -16,7 +17,10 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.ContextConfiguration;
@ -145,4 +149,30 @@ public class UserRepositoryIntegrationTest {
assertThat(users.size(), is(1));
assertThat(page.getTotalPages(), is(2));
}
@Test
public void givenUserExistsWithIndexAddedFromMapping_whenCheckingIndex_thenIndexIsExisted() {
User user = new User();
user.setName("Brendan");
EmailAddress emailAddress = new EmailAddress("a@gmail.com");
mongoOps.insert(emailAddress);
user.setEmailAddress(emailAddress);
mongoOps.insert(user);
List<IndexInfo> indexInfos = mongoOps.indexOps("user").getIndexInfo();
assertThat(indexInfos.size(), is(1));
}
@Test
public void givenUserExistsWithIndexAddedFromCode_whenCheckingIndex_thenIndexIsExisted() {
User user = new User();
user.setName("Brendan");
mongoOps.indexOps(User.class).ensureIndex(new Index().on("name", Direction.ASC));
mongoOps.insert(user);
List<IndexInfo> indexInfos = mongoOps.indexOps("user").getIndexInfo();
assertThat(indexInfos.size(), is(2));
}
}