mongodb 搭配JSR-303验证框架

在mongodb中,如何对一个对象插入collection时进行验证呢?因为mongodb毕竟是NOSQL,跟关系数据库有点不同,所以其中一个校验的思路方法,是使用JSR-303的标准校验,
这个在HIBERNATE 4和spring 3中其实已经支持了,下面讲解下方法:

1) MAVEN中如下配置
  
<dependency>    <groupId>javax.validation</groupId>    <artifactId>validation-api</artifactId>    <version>1.0.0.GA</version>    <scope>compile</scope></dependency> <dependency>    <groupId>org.hibernate</groupId>    <artifactId>hibernate-validator</artifactId>    <version>4.2.0.Final</version></dependency>



2 spring 中引入验证框架
 
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>


3 因为要在对象保存前进行验证,因此可以扩展spring for mongodb中的
AbstractMongoEventListener 类进行监听,重写其 onBeforeSave方法
  
@Component
public class BeforeSaveValidator extends AbstractMongoEventListener
 {   
  @Override    
public void onBeforeSave(Object source, DBObject dbo)
 {     
   // do validation here  
  }
}


4 然后调用validator.validate方法进行验证,返回的是一个set,就是哪些不符合要求的,代码如下:
  
@Componentpublic 
class BeforeSaveValidator extends AbstractMongoEventListener 
{  
   @Autowired
    private Validator validator;   
  @Override  
  public void onBeforeSave(Object source, DBObject dbo)
 {        Set<ConstraintViolation<Object>> violations = validator.validate(source);      
   if (violations.size() > 0) 
{ 
           throw new ConstraintViolationException(violations);    
    }
    }
}


5 写个类测试下,用注解:
  
public class User 
{    @Size(min = 10) 
   private String name;  
   @Min(18) 
   private Integer age;  
   public User(String name, Integer age) 
{       
 this.name = name;   
     this.age = age;  
  }    
 public String getName()
 {    
    return name;   
 }   
  public Integer getAge() { 
       return age;
    }
}


6 单元测试下
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ValidationTest 
{    @Autowired 
   private MongoTemplate mongoTemplate;
     @Test  
  public void shouldThrowValidationException() 
{      
  User user = new User("john", 17);   
      try {       
     mongoTemplate.save(user);       
     fail();      
  } catch (ConstraintViolationException e) 
{            assertThat(e.getViolations()).hasSize(2);   
     } 
   }
}

猜你喜欢

转载自jackyrong.iteye.com/blog/1665691