Morphia 学习六 扩展使用

Validation  验证
Morphia使用JSR303验证注释

在应用启动或者创建Morphia对象的时候,调用

new ValidationExtension(morphia);

使用
        
下面例子使用Hibernate验证
import org.hibernate.validator.constraints.Email;

@Entity
public class Userlike {
        @Id ObjectId id;
        @Email String email;
}


实现
        轻量级的封装JSR303 API,使用一个全局对象拦截器监听方法生命周期来验证,你可以添加任何JSR303的实现到classpath。
package com.google.code.morphia.validation;

import java.util.Set;

import javax.validation.Configuration;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import com.google.code.morphia.AbstractEntityInterceptor;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.mapping.Mapper;
import com.mongodb.DBObject;

/**
 * @author [email protected]
 */
public class ValidationExtension extends AbstractEntityInterceptor
{
    private ValidatorFactory validationFactory;
    private Mapper mapper;

    @Deprecated
    public ValidationExtension()
    {
        // use the new ValidationExtension(morphia) convention
    }

    public ValidationExtension(final Morphia m)
    {
        final Configuration<?> configuration = Validation.byDefaultProvider().configure();
        this.validationFactory = configuration.buildValidatorFactory();

        m.getMapper().addInterceptor(this);
    }

    @Override
    public void prePersist(final Object ent, final DBObject dbObj, final Mapper mapr)
    {
        final Set validate = this.validationFactory.getValidator().validate(ent);
        if (!validate.isEmpty())
        {
            throw new VerboseJSR303ConstraintViolationException(validate);
        }
    }
}



SLF4J

       This is a simple extension to Morphia to redirect logging to SFL4J.
应用启动时,只静态加载一次
MorphiaLoggerFactory.registerLogger(SLF4JLoggerImplFactory.class);









你可能感兴趣的:(Hibernate,validation,扩展,redirect,extension,deprecated)