JIRA: DATADOC-70: Trying to fix problem with indexes being wiped out in the tests, trying to make sure indexes get created properly. Now tests do not wipe out database automatically.

This commit is contained in:
Jon Brisbin
2011-03-25 13:52:53 -05:00
committed by J. Brisbin
parent 0468ba3ad9
commit 635e156bc0
5 changed files with 51 additions and 64 deletions

1
.gitignore vendored
View File

@@ -9,3 +9,4 @@ target
.project .project
.classpath .classpath
src/ant/.ant-targets-upload-dist.xml src/ant/.ant-targets-upload-dist.xml
atlassian-ide-plugin.xml

View File

@@ -45,7 +45,7 @@ import org.w3c.dom.Element;
public class MongoMappingConverterParser extends AbstractBeanDefinitionParser { public class MongoMappingConverterParser extends AbstractBeanDefinitionParser {
static final String MAPPING_CONTEXT = "mappingContext"; static final String MAPPING_CONTEXT = "mappingContext";
private static final String MAPPING_CONFIGURATION_HELPER = "mappingConfigurationHelper"; private static final String INDEX_HELPER = "indexCreationHelper";
private static final String TEMPLATE = "mongoTemplate"; private static final String TEMPLATE = "mongoTemplate";
private static final String BASE_PACKAGE = "base-package"; private static final String BASE_PACKAGE = "base-package";
@@ -85,13 +85,13 @@ public class MongoMappingConverterParser extends AbstractBeanDefinitionParser {
converterBuilder.addPropertyReference("mongo", StringUtils.hasText(mongoRef) ? mongoRef : "mongo"); converterBuilder.addPropertyReference("mongo", StringUtils.hasText(mongoRef) ? mongoRef : "mongo");
try { try {
registry.getBeanDefinition(MAPPING_CONFIGURATION_HELPER); registry.getBeanDefinition(INDEX_HELPER);
} catch (NoSuchBeanDefinitionException ignored) { } catch (NoSuchBeanDefinitionException ignored) {
String templateRef = element.getAttribute("mongo-template-ref"); String templateRef = element.getAttribute("mongo-template-ref");
BeanDefinitionBuilder mappingConfigHelperBuilder = BeanDefinitionBuilder.genericBeanDefinition(MongoPersistentEntityIndexCreator.class); BeanDefinitionBuilder indexHelperBuilder = BeanDefinitionBuilder.genericBeanDefinition(MongoPersistentEntityIndexCreator.class);
mappingConfigHelperBuilder.addConstructorArgValue(new RuntimeBeanReference(ctxRef)); indexHelperBuilder.addConstructorArgValue(new RuntimeBeanReference(ctxRef));
mappingConfigHelperBuilder.addConstructorArgValue(new RuntimeBeanReference(StringUtils.hasText(templateRef) ? templateRef : TEMPLATE)); indexHelperBuilder.addConstructorArgValue(new RuntimeBeanReference(StringUtils.hasText(templateRef) ? templateRef : TEMPLATE));
registry.registerBeanDefinition(MAPPING_CONFIGURATION_HELPER, mappingConfigHelperBuilder.getBeanDefinition()); registry.registerBeanDefinition(INDEX_HELPER, indexHelperBuilder.getBeanDefinition());
} }
return converterBuilder.getBeanDefinition(); return converterBuilder.getBeanDefinition();

View File

@@ -35,7 +35,7 @@ import org.springframework.data.util.TypeInformation;
* @author Jon Brisbin <jbrisbin@vmware.com> * @author Jon Brisbin <jbrisbin@vmware.com>
*/ */
public class MongoMappingContext extends BasicMappingContext { public class MongoMappingContext extends BasicMappingContext {
public MongoMappingContext() { public MongoMappingContext() {
augmentSimpleTypes(); augmentSimpleTypes();
} }
@@ -67,7 +67,7 @@ public class MongoMappingContext extends BasicMappingContext {
@Override @Override
public BasicPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, public BasicPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor,
TypeInformation information) throws MappingConfigurationException { TypeInformation information) throws MappingConfigurationException {
return new MongoPersistentProperty(field, descriptor, information); return new MongoPersistentProperty(field, descriptor, information);
} }

View File

@@ -18,8 +18,6 @@ package org.springframework.data.document.mongodb.mapping;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -46,40 +44,38 @@ import org.springframework.util.Assert;
/** /**
* Component that inspects {@link MongoPersistentEntity} instances contained in the given {@link MongoMappingContext} * Component that inspects {@link MongoPersistentEntity} instances contained in the given {@link MongoMappingContext}
* for indexing metadata and ensures the indexes to be available. * for indexing metadata and ensures the indexes to be available.
* *
* @author Jon Brisbin <jbrisbin@vmware.com> * @author Jon Brisbin <jbrisbin@vmware.com>
* @author Oliver Gierke * @author Oliver Gierke
*/ */
public class MongoPersistentEntityIndexCreator implements ApplicationListener<MappingContextEvent>{ public class MongoPersistentEntityIndexCreator implements ApplicationListener<MappingContextEvent> {
private static final Logger log = LoggerFactory.getLogger(MongoPersistentEntityIndexCreator.class); private static final Logger log = LoggerFactory.getLogger(MongoPersistentEntityIndexCreator.class);
private Map<String, CompoundIndex> compoundIndexes = new HashMap<String, CompoundIndex>();
private Map<String, Indexed> fieldIndexes = new HashMap<String, Indexed>();
private Set<Class<?>> classesSeen = Collections.newSetFromMap(new ConcurrentHashMap<Class<?>, Boolean>()); private Set<Class<?>> classesSeen = Collections.newSetFromMap(new ConcurrentHashMap<Class<?>, Boolean>());
private final MongoTemplate mongoTemplate; private final MongoTemplate mongoTemplate;
public MongoPersistentEntityIndexCreator(MongoMappingContext mappingContext, MongoTemplate mongoTemplate) { public MongoPersistentEntityIndexCreator(MongoMappingContext mappingContext, MongoTemplate mongoTemplate) {
Assert.notNull(mongoTemplate); Assert.notNull(mongoTemplate);
Assert.notNull(mappingContext); Assert.notNull(mappingContext);
this.mongoTemplate = mongoTemplate; this.mongoTemplate = mongoTemplate;
for (MongoPersistentEntity<?> entity : mappingContext.getPersistentEntities()) { for (MongoPersistentEntity<?> entity : mappingContext.getPersistentEntities()) {
checkForIndexes(entity); checkForIndexes(entity);
} }
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent) * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
*/ */
public void onApplicationEvent(MappingContextEvent event) { public void onApplicationEvent(MappingContextEvent event) {
checkForIndexes((MongoPersistentEntity<?>) event.getPersistentEntity()); checkForIndexes((MongoPersistentEntity<?>) event.getPersistentEntity());
} }
protected void checkForIndexes(MongoPersistentEntity<?> entity) { protected void checkForIndexes(MongoPersistentEntity<?> entity) {
Class<?> type = entity.getType(); final Class<?> type = entity.getType();
if (!classesSeen.contains(type)) { if (!classesSeen.contains(type)) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Analyzing class " + type + " for index information."); log.debug("Analyzing class " + type + " for index information.");
@@ -102,12 +98,9 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener<Ma
if ("".equals(indexColl)) { if ("".equals(indexColl)) {
indexColl = type.getSimpleName().toLowerCase(); indexColl = type.getSimpleName().toLowerCase();
} }
if (!compoundIndexes.containsKey(indexColl)) { ensureIndex(indexColl, index.name(), index.def(), index.direction(), index.unique(), index.dropDups(), index.sparse());
ensureIndex(indexColl, index.name(), index.def(), index.direction(), index.unique(), index.dropDups(), index.sparse()); if (log.isDebugEnabled()) {
if (log.isDebugEnabled()) { log.debug("Created compound index " + index);
log.debug("Created compound index " + index);
}
compoundIndexes.put(indexColl, index);
} }
} }
} }
@@ -117,16 +110,17 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener<Ma
Field field = persistentProperty.getField(); Field field = persistentProperty.getField();
if (field.isAnnotationPresent(Indexed.class)) { if (field.isAnnotationPresent(Indexed.class)) {
Indexed index = field.getAnnotation(Indexed.class); Indexed index = field.getAnnotation(Indexed.class);
String name = index.name();
if ("".equals(name)) {
name = field.getName();
}
String collection = index.collection(); String collection = index.collection();
if ("".equals(collection)) { if ("".equals(collection)) {
collection = field.getName(); collection = type.getSimpleName().toLowerCase();
} }
if (!fieldIndexes.containsKey(collection)) { ensureIndex(collection, name, null, index.direction(), index.unique(), index.dropDups(), index.sparse());
ensureIndex(collection, index.name(), null, index.direction(), index.unique(), index.dropDups(), index.sparse()); if (log.isDebugEnabled()) {
if (log.isDebugEnabled()) { log.debug("Created property index " + index);
log.debug("Created property index " + index);
}
fieldIndexes.put(collection, index);
} }
} }
} }
@@ -135,6 +129,7 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener<Ma
classesSeen.add(type); classesSeen.add(type);
} }
} }
protected void ensureIndex(String collection, protected void ensureIndex(String collection,
@@ -154,9 +149,7 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener<Ma
defObj.put(name, (direction == IndexDirection.ASCENDING ? 1 : -1)); defObj.put(name, (direction == IndexDirection.ASCENDING ? 1 : -1));
} }
DBObject opts = new BasicDBObject(); DBObject opts = new BasicDBObject();
if (!"".equals(name)) { //opts.put("name", name + "_idx");
opts.put("name", name);
}
opts.put("dropDups", dropDups); opts.put("dropDups", dropDups);
opts.put("sparse", sparse); opts.put("sparse", sparse);
opts.put("unique", unique); opts.put("unique", unique);

View File

@@ -24,14 +24,11 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.data.document.mongodb.MongoTemplate; import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.data.document.mongodb.convert.MappingMongoConverter;
import org.springframework.data.document.mongodb.query.Criteria; import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query; import org.springframework.data.document.mongodb.query.Query;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
@@ -49,26 +46,7 @@ public class MappingTests {
@Autowired @Autowired
MongoTemplate template; MongoTemplate template;
@Autowired @Autowired
MappingMongoConverter mappingConverter; MongoMappingContext mappingContext;
@Test
public void setUp() {
template.dropCollection("person");
template.dropCollection("account");
}
@Test
public void testConvertSimpleProperty() {
PersonPojo p = new PersonPojo(1234, "Person", "Pojo");
DBObject dbo = new BasicDBObject();
mappingConverter.write(p, dbo);
assertEquals(dbo.get("ssn"), 1234);
PersonPojo p2 = mappingConverter.read(PersonPojo.class, dbo);
assertEquals(p.getFirstName(), p2.getFirstName());
}
@Test @Test
public void testPersonPojo() { public void testPersonPojo() {
@@ -76,7 +54,7 @@ public class MappingTests {
template.insert(p); template.insert(p);
assertNotNull(p.getId()); assertNotNull(p.getId());
List<PersonPojo> result = template.find(new Query(Criteria.where("_id").is(p.getId())), PersonPojo.class); List<PersonPojo> result = template.find(new Query(Criteria.where("ssn").is(12345)), PersonPojo.class);
assertThat(result.size(), is(1)); assertThat(result.size(), is(1));
assertThat(result.get(0).getSsn(), is(12345)); assertThat(result.get(0).getSsn(), is(12345));
} }
@@ -141,14 +119,29 @@ public class MappingTests {
template.save("person", p); template.save("person", p);
assertNotNull(p.getId()); assertNotNull(p.getId());
}
@Test
public void testReadEntity() {
List<Person> result = template.find(new Query(Criteria.where("ssn").is(123456789)), Person.class); List<Person> result = template.find(new Query(Criteria.where("ssn").is(123456789)), Person.class);
assertThat(result.size(), is(1)); assertThat(result.size(), is(1));
assertThat(result.get(0).getAddress().getCountry(), is("USA")); assertThat(result.get(0).getAddress().getCountry(), is("USA"));
assertThat(result.get(0).getAccounts(), notNullValue()); assertThat(result.get(0).getAccounts(), notNullValue());
} }
@Test
public void testUniqueIndex() {
Address addr = new Address();
addr.setLines(new String[]{"1234 W. 1st Street", "Apt. 12"});
addr.setCity("Anytown");
addr.setPostalCode(12345);
addr.setCountry("USA");
Person p1 = new Person(1234567890, "John", "Doe", 37, addr);
Person p2 = new Person(1234567890, "John", "Doe", 37, addr);
template.insert("person", p1);
template.insert("person", p2);
List<Person> result = template.find(new Query(Criteria.where("ssn").is(1234567890)), Person.class);
assertThat(result.size(), is(1));
}
} }