Search in sources :

Example 1 with UniqueIndexOnValue

use of org.mongodb.morphia.entities.UniqueIndexOnValue in project morphia by mongodb.

the class TestIndexed method shouldThrowExceptionWhenAddingADuplicateValueForAUniqueIndex.

@Test
public void shouldThrowExceptionWhenAddingADuplicateValueForAUniqueIndex() {
    getMorphia().map(UniqueIndexOnValue.class);
    getDs().ensureIndexes();
    long value = 7L;
    try {
        final UniqueIndexOnValue entityWithUniqueName = new UniqueIndexOnValue();
        entityWithUniqueName.setValue(value);
        entityWithUniqueName.setUnique(1);
        getDs().save(entityWithUniqueName);
        final UniqueIndexOnValue entityWithSameName = new UniqueIndexOnValue();
        entityWithSameName.setValue(value);
        entityWithSameName.setUnique(2);
        getDs().save(entityWithSameName);
        Assert.fail("Should have gotten a duplicate key exception");
    } catch (Exception ignored) {
    }
    value = 10L;
    try {
        final UniqueIndexOnValue first = new UniqueIndexOnValue();
        first.setValue(1);
        first.setUnique(value);
        getDs().save(first);
        final UniqueIndexOnValue second = new UniqueIndexOnValue();
        second.setValue(2);
        second.setUnique(value);
        getDs().save(second);
        Assert.fail("Should have gotten a duplicate key exception");
    } catch (Exception ignored) {
    }
}
Also used : UniqueIndexOnValue(org.mongodb.morphia.entities.UniqueIndexOnValue) DuplicateKeyException(com.mongodb.DuplicateKeyException) MappingException(org.mongodb.morphia.mapping.MappingException) Test(org.junit.Test)

Example 2 with UniqueIndexOnValue

use of org.mongodb.morphia.entities.UniqueIndexOnValue in project morphia by mongodb.

the class TestIndexed method testUniqueIndexedEntity.

@Test(expected = DuplicateKeyException.class)
public void testUniqueIndexedEntity() throws Exception {
    getDs().ensureIndexes();
    assertThat(getDs().getCollection(UniqueIndexOnValue.class).getIndexInfo(), hasIndexNamed("l_ascending"));
    getDs().save(new UniqueIndexOnValue("a"));
    // this should throw...
    getDs().save(new UniqueIndexOnValue("v"));
}
Also used : UniqueIndexOnValue(org.mongodb.morphia.entities.UniqueIndexOnValue) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)2 UniqueIndexOnValue (org.mongodb.morphia.entities.UniqueIndexOnValue)2 DuplicateKeyException (com.mongodb.DuplicateKeyException)1 MappingException (org.mongodb.morphia.mapping.MappingException)1