Search in sources :

Example 6 with DocumentValidation

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

the class TestDocumentValidation method saveToNewCollection.

@Test
public void saveToNewCollection() {
    getMorphia().map(DocumentValidation.class);
    final Document validator = Document.parse("{ number : { $gt : 10 } }");
    String collection = "newdocs";
    addValidation(validator, collection);
    try {
        getAds().save(collection, new DocumentValidation("Harold", 8, new Date()));
        fail("Document validation should have complained");
    } catch (WriteConcernException e) {
    // expected
    }
    getAds().save(collection, new DocumentValidation("Harold", 8, new Date()), new InsertOptions().bypassDocumentValidation(true));
    Query<DocumentValidation> query = getAds().createQuery(collection, DocumentValidation.class).field("number").equal(8);
    Assert.assertNotNull(query.get());
}
Also used : DocumentValidation(org.mongodb.morphia.entities.DocumentValidation) WriteConcernException(com.mongodb.WriteConcernException) Document(org.bson.Document) Date(java.util.Date) Test(org.junit.Test)

Example 7 with DocumentValidation

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

the class TestDocumentValidation method createValidation.

@Test
public void createValidation() {
    getMorphia().map(DocumentValidation.class);
    getDs().enableDocumentValidation();
    assertEquals(Document.parse(DocumentValidation.class.getAnnotation(Validation.class).value()), getValidator());
    try {
        getDs().save(new DocumentValidation("John", 1, new Date()));
        fail("Document should have failed validation");
    } catch (WriteConcernException e) {
        assertTrue(e.getMessage().contains("Document failed validation"));
    }
    getDs().save(new DocumentValidation("Harold", 100, new Date()));
}
Also used : DocumentValidation(org.mongodb.morphia.entities.DocumentValidation) Validation(org.mongodb.morphia.annotations.Validation) DocumentValidation(org.mongodb.morphia.entities.DocumentValidation) WriteConcernException(com.mongodb.WriteConcernException) Date(java.util.Date) Test(org.junit.Test)

Aggregations

Date (java.util.Date)7 Test (org.junit.Test)7 DocumentValidation (org.mongodb.morphia.entities.DocumentValidation)7 WriteConcernException (com.mongodb.WriteConcernException)6 Document (org.bson.Document)2 Validation (org.mongodb.morphia.annotations.Validation)2 MongoCommandException (com.mongodb.MongoCommandException)1 MongoWriteException (com.mongodb.MongoWriteException)1 MongoDatabase (com.mongodb.client.MongoDatabase)1