Morphia 学习三 自定义注解、转换器

自定义注解

在特殊的情况下,定义服务端注解,减少配置。下面代码为注解的使用:

注解类:

import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
@Retention(RetentionPolicy.RUNTIME)  
@Target({ElementType.FIELD})  
public  @interface Lowercase {  
}
使用类:
@Entity  
public class MorphiaInfo {  
    private @Id String id;  
    //自定义注释的使用  
    @Lowercase  
    private String morphiaName;  
    private String version; 
拦截器:
import com.google.code.morphia.EntityInterceptor;  
import com.google.code.morphia.mapping.MappedClass;  
import com.google.code.morphia.mapping.MappedField;  
import com.google.code.morphia.mapping.Mapper;  
import com.mongodb.DBObject;  
/** 
 * 使用拦截器机制的使用用于特定的处理 
 */  
public class ToLowercaseHelper implements EntityInterceptor {  
      
    public void postLoad(Object ent, DBObject dbObj, Mapper mapr) {}        
    public void postPersist(Object ent, DBObject dbObj, Mapper mapr) {}  
    /** 
     * 保存的前的拦截 
     */  
    public void preSave(Object ent, DBObject dbObj, Mapper mapr) {}  
  
    /** 
     * 加载前的操作 
     */  
    public void preLoad(Object ent, DBObject dbObj, Mapper mapr) {}  
  
    /** 
     * 持久化前的处理 
     * (non-Javadoc) 
     * @see com.google.code.morphia.EntityInterceptor#prePersist(java.lang.Object, com.mongodb.DBObject, com.google.code.morphia.mapping.Mapper) 
     */  
    public void prePersist(Object ent, DBObject dbObj, Mapper mapr) {  
        //获取映射的类  
        MappedClass mc = mapr.getMappedClass(ent);  
        //获取映射的特定注释的类字段  
        List<MappedField> toLowercase = mc.getFieldsAnnotatedWith(Lowercase.class);  
        //针对映射特定的注释类的处理  
        for (MappedField mf : toLowercase) {  
            try {  
                Object fieldValue = mf.getFieldValue(ent);  
                dbObj.put(mf.getNameToStore() + "_lowercase", fieldValue.toString().toLowerCase());  
            } catch (Exception e) {  
                throw new RuntimeException(e);  
            }  
        }  
    }  
}  




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值