Mongo的ORM框架的学习Morphia(十一) morphia自定义注解、转换器的使用

转自:http://topmanopensource.iteye.com/blog/1439689

         http://topmanopensource.iteye.com/blog/1439692

 

一:自定义注解的使用

 

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

注解类:

package com.easyway.mongodb.morphia.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 
 * @Title: 自定义注释的使用
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public  @interface Lowercase {
}
 
package com.easyway.mongodb.morphia.annotation;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
/**
 * 用于存储MorphiaInfo的信息
 * @Title: 
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
@Entity
public class MorphiaInfo {
	private @Id String id;
	//自定义注释的使用
	@Lowercase
	private String morphiaName;
	private String version;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getMorphiaName() {
		return morphiaName;
	}
	public void setMorphiaName(String morphiaName) {
		this.morphiaName = morphiaName;
	}
	public String getVersion() {
		return version;
	}
	public void setVersion(String version) {
		this.version = version;
	}
	
}
 
package com.easyway.mongodb.morphia.annotation;

import java.util.List;

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;
/**
 * 使用拦截器机制的使用用于特定的处理
 * 
 * @Title: 
 * @Description: 实现自定义注释的使用
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
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);
			}
		}
	}
}

 

package com.easyway.mongodb.morphia.annotation;

import com.google.code.morphia.AdvancedDatastore;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.mapping.MappedField;
import com.mongodb.DB;
import com.mongodb.Mongo;
/**
 * 
 * @Title: 简单的测试类
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
public class AnnotationApp {
	public static void main(String[] args)  {
		try {
		     String dbName="test";
		     //创建一个Mongo对象
		     Mongo mongo = new Mongo("localhost");
		     //获取Mongo的数据库对象
		     DB db = mongo.getDB(dbName);
		     //创建一个Morphia对象
		     Morphia morphia = new Morphia();
		     //创建一个Datastore对象用于操作数据
		     Datastore ds= morphia.createDatastore(mongo, db.getName());
		     AdvancedDatastore ads = (AdvancedDatastore) ds;
		     //映射字段添加对应的自定义注释的注册
			 MappedField.interestingAnnotations.add(Lowercase.class);
			 //映射mapper中添加相关的拦截器
			 morphia.getMapper().addInterceptor(new ToLowercaseHelper());
			 //设置映射的类
			 morphia.map(MorphiaInfo.class);
			 
			 //保存一个mongo对象
			 MorphiaInfo u = new MorphiaInfo();
			 u.setVersion("Morphia V1.0");
			 u.setMorphiaName("MorphiaName");
			 ds.save(u);
			 
			 //查找一个mongo对象
			MorphiaInfo uScott = ds.find(MorphiaInfo.class).disableValidation().filter("morphiaName_lowercase", u.getMorphiaName().toLowerCase()).get();
	        System.out.println("uScott="+uScott.getMorphiaName());
	        
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
 

 

 

二:自定义转换器的使用

 

       在Morphia中为什么各种数据库可以自由转换为Java对象呢?主要采用转换器机制实现实现字符串和Java对象之间的转换,转换器类需要实现TypeConvertor,如下:

 

public  class FooConverter extends TypeConverter implements SimpleValueConverter 

 

下面讲解转换器的使用:

package com.easyway.mongodb.morphia.converter;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-4
 * @author 
 * @version 1.0
 */
@Entity(noClassnameStored=false,value="animail")
public class Animail {
	@Id
	private String id;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	

}
 
package com.easyway.mongodb.morphia.converter;

import java.util.HashMap;

import java.util.Map;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-4
 * @author 
 * @version 1.0
 */
@Entity(noClassnameStored=false,value="animail")
public class Dog extends Animail{
	private static final long serialVersionUID = 1L;
	@Embedded
	Map<String, Foo> foo = new HashMap<String, Foo>();
}
 
package com.easyway.mongodb.morphia.converter;

import net.sf.json.JSONObject;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-4
 * @author 
 * @version 1.0
 */
public  class Foo {
	private String name;
	private String email;
	
	Foo(){}
	public Foo(String name,String email) {
		this.name = name;
		this.email=email;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return JSONObject.fromObject(this).toString();
	}
}

 

转换器类如下:

package com.easyway.mongodb.morphia.converter;

import net.sf.json.JSONObject;

import com.google.code.morphia.converters.SimpleValueConverter;
import com.google.code.morphia.converters.TypeConverter;
import com.google.code.morphia.mapping.MappedField;
import com.google.code.morphia.mapping.MappingException;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-4
 * @author 
 * @version 1.0
 */
public  class FooConverter extends TypeConverter implements SimpleValueConverter  {
	
	public boolean done;
	
	public FooConverter() {
		super(Foo.class);
	}
	
	/**
	 * 
	 */
	@Override
	public Object decode(Class targetClass, Object fromDBObject, MappedField mf)
			throws MappingException {
		if(fromDBObject==null){
			return null;
		}
		JSONObject jsonObject=JSONObject.fromObject(fromDBObject);
		return JSONObject.toBean(jsonObject, targetClass);
	}
	
	@Override
	public Object encode(Object value, MappedField optionalExtraInfo) {
		done = true;
		return JSONObject.fromObject(value).toString();
	}
	
	public boolean didConversion() {
		return done;
	}
}
 
package com.easyway.mongodb.morphia.converter;

import java.util.LinkedList;
import java.util.List;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;

/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-4
 * @author 
 * @version 1.0
 */
@Entity(noClassnameStored=false,value="animail")
public class Pig  extends Animail{
	private static final long serialVersionUID = 1L;
	@Embedded
	List<Foo> foo = new LinkedList<Foo>();
	
}

 

测试如下:

package com.easyway.mongodb.morphia.converter;

import java.net.UnknownHostException;

import com.google.code.morphia.AdvancedDatastore;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-4
 * @author 
 * @version 1.0
 */
public class FooConverterApp {
    
    
    public static void main(String[] args) throws UnknownHostException, MongoException {
    	
    	Morphia morphia = new Morphia();
    	Mongo mongo = new Mongo("localhost");
        DB db= mongo.getDB("morphia_test");
        Datastore ds = morphia.createDatastore(mongo, db.getName());
        AdvancedDatastore ads = (AdvancedDatastore) ds;
        morphia.map(Pig.class).map(Dog.class).map(Animail.class);
        FooConverter  fc=new FooConverter();
    	
    	//morphia.getMapper().getConverters().addConverter(fc);
    	Dog e = new Dog();
		e.foo.put("bar",new Foo("bar"," a bar"));
		e.foo.put("big",new Foo("dog","a dog"));
		ds.save(e);
		System.out.println(e.foo.get("bar").toString());
		Pig pig=new Pig();
		pig.foo.add(new Foo("a","b"));
		pig.foo.add(new Foo("b","c"));
		ds.save(pig);
		
	}
    
}
 

 

 

你可能感兴趣的:(Morphia)