Morphiaは3つのカスタム注釈、変換器を学ぶ
カスタム注記
特別な場合、サービス側注釈を定義し、構成を減らす.次のコードは注釈の使用です.注記クラス:
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);
}
}
}
}