Morphia是Google提供的MongoDB的封装接口,本身功能已经比较强大,在调研了一些资料后,有些Morphia与spring封装的接口,发现使用时还是有些繁琐。特意查看Morphia的源码,集成了一个简易接口。通过MongoDAO即可直接使用morphia接口,非常方便。
在实际使用中,只要编写Mongo数据类及对应的数据操作类(LoginUserItem,java、LoginUserDb.java)即可调用。
1、mongoDAO.java
package com.iflytek.common.mongo;
import org.bson.types.ObjectId;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Key;
import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;
import com.google.code.morphia.query.UpdateOperations;
import com.google.code.morphia.query.UpdateResults;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
public class MongoDAO extends BasicDAO {
public MongoDAO(Class entityClass, Datastore ds) {
super(entityClass, ds);
}
@Override
public long count() {
return super.count();
}
@Override
public long count(Query q) {
return super.count(q);
}
@Override
public long count(String key, Object value) {
return super.count(key, value);
}
@Override
public Query createQuery() {
return super.createQuery();
}
public Query createQuery(String key, Object value) {
return super.createQuery().field(key).equal(value);
}
@Override
public UpdateOperations createUpdateOperations() {
return super.createUpdateOperations();
}
public WriteResult delete(T entity, boolean isSafe) {
WriteConcern wc = new WriteConcern();
if (isSafe) {
wc = WriteConcern.SAFE;
} else {
wc = WriteConcern.NORMAL;
}
return super.delete(entity, wc);
}
@Override
public WriteResult delete(T entity, WriteConcern wc) {
// TODO Auto-generated method stub
return super.delete(entity, wc);
}
@Override
public WriteResult delete(T entity) {
return super.delete(entity);
}
@Override
public WriteResult deleteByQuery(Query q) {
return super.deleteByQuery(q);
}
public WriteResult deleteByQuery(String key, Object value) {
return super.deleteByQuery(createQuery().field(key).equal(value));
}
@Override
public void ensureIndexes() {
super.ensureIndexes();
}
@Override
public boolean exists(Query q) {
return super.exists(q);
}
@Override
public boolean exists(String key, Object value) {
return super.exists(key, value);
}
@Override
public QueryResults find() {
return super.find();
}
@Override
public QueryResults find(Query q) {
return super.find(q);
}
@Override
public T findOne(Query q) {
return super.findOne(q);
}
@Override
public T findOne(String key, Object value) {
return super.findOne(key, value);
}
@Override
public Key save(T entity, WriteConcern wc) {
return super.save(entity, wc);
}
public Key save(T entity, boolean isSafe) {
WriteConcern wc = new WriteConcern();
if (isSafe) {
wc = WriteConcern.SAFE;
} else {
wc = WriteConcern.NORMAL;
}
return super.save(entity, wc);
}
@Override
public Key save(T entity) {
return super.save(entity);
}
@Override
public UpdateResults update(Query q, UpdateOperations ops) {
return super.update(q, ops);
}
public UpdateResults update(Query q, UpdateOperations ops,
boolean createIfMissing) {
return ds.update(q, ops, createIfMissing);
}
@Override
public UpdateResults updateFirst(Query q, UpdateOperations ops) {
return super.updateFirst(q, ops);
}
public UpdateResults updateFirst(Query q, UpdateOperations ops,
boolean createIfMissing) {
return ds.update(q, ops, createIfMissing);
}
public T findAndDelete(Query q) {
return ds.findAndDelete(q);
}
public T findAndModify(Query q, UpdateOperations ops) {
return ds.findAndModify(q, ops);
}
public T findAndModify(Query q, UpdateOperations ops,
boolean oldVersion) {
return ds.findAndModify(q, ops, oldVersion);
}
public T findAndModify(Query q, UpdateOperations ops,
boolean oldVersion, boolean createIfMissing) {
return ds.findAndModify(q, ops, oldVersion, createIfMissing);
}
}
2、MongoUtil.java
package com.iflytek.common.mongo;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.iflytek.common.util.ReadProp;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
public class MongoUtil {
/** 读取配置文件 */
private static ReadProp readProp = new ReadProp();
private static String mongodb_ip = readProp.readValue("MONGO_IP");
private static int mongodb_port = Integer.parseInt(readProp
.readValue("MONGO_PORT"));
public static String mongo_dbname = readProp.readValue("MONGO_DB");
// 连接池
private static int poolSize = Integer.parseInt(readProp
.readValue("MONGO_POOLSIZE"));
public static Datastore getDb() {
return getDb( mongodb_ip, mongodb_port, poolSize, mongo_dbname);
}
public static Datastore getDb( String host, int port,
int size, String dbName) {
MongoOptions option = new MongoOptions();
if (size == 0) {
size = 50;
}
Mongo mongo = null;
option.connectionsPerHost = size;
option.autoConnectRetry = true;
option.threadsAllowedToBlockForConnectionMultiplier = 10;
option.w = 0;
option.safe = true;
try {
ServerAddress addr = new ServerAddress(host, port);
mongo = new Mongo(addr, option);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Morphia morphia = new Morphia();
Datastore ds = morphia.createDatastore(mongo, dbName);
ds.ensureIndexes(); // 在标记为@Id的类属性上创建索引
ds.ensureCaps(); // 设置默认的mongoDB集合容量
return ds;
}
/**
* 解决时差8小时问题
*
* @param date
* @return
*/
public static Date mongoDateTran(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = format.format(date);
format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
try {
return format.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return date;
}
}
}
3、用户数据类
package com.iflytek.chatms.db.data;
import java.util.Date;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Indexed;
import com.google.code.morphia.utils.IndexDirection;
@Entity("LoginUserInfo")
public class LoginUserItem {
@Id
private ObjectId id;
@Indexed(value = IndexDirection.ASC, name = "login_mail_index")
private String email;
@Indexed(value = IndexDirection.ASC, name = "login_phonenum_index")
private String phonenum;
private String password;
@Indexed(value = IndexDirection.ASC, name = "login_imei_index")
private String imei;
@Indexed(value = IndexDirection.ASC, name = "login_name_index")
private String name;
private String imgpath;
private Date create_time;
private Date update_time;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImgpath() {
return imgpath;
}
public void setImgpath(String imgpath) {
this.imgpath = imgpath;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public Date getUpdate_time() {
return update_time;
}
public void setUpdate_time(Date update_time) {
this.update_time = update_time;
}
}
package com.iflytek.chatms.db;
import java.util.Date;
import org.apache.log4j.Logger;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.iflytek.chatms.db.data.LoginUserItem;
import com.iflytek.common.mongo.MongoDAO;
import com.iflytek.common.mongo.MongoUtil;
public class LoginUserDb {
private static final Logger LOG = Logger.getLogger(LoginUserDb.class);
private static MongoDAO mongodb = new MongoDAO(
LoginUserItem.class, MongoUtil.getDb());
public static LoginUserItem getUserInfoByPhonenum(String phonenum) {
LOG.info("[getUserInfoByPhonenum] phonenum=" + phonenum);
LoginUserItem dbitem = mongodb.findOne(DbConfig.PHONENUM, phonenum);
return dbitem;
}
public static void changePassword(String phonenum, String password) {
LOG.info("[changePassword] phonenum=" + phonenum);
Query updateQuery = mongodb.createQuery()
.field(DbConfig.PHONENUM).equal(phonenum);
UpdateOperations ops = mongodb.createUpdateOperations()
.set(DbConfig.PASSWORD, password)
.set("update_time", MongoUtil.mongoDateTran(new Date()));
mongodb.update(updateQuery, ops);
}
public static void RegisterByPhonenum(String imei, String phonenum,
String password, String name, String imgpath) {
LOG.info("[RegisterByPhonenum] phonenum=" + phonenum + ",password="
+ password + ",imei=" + imei + ",name=" + name + ",imgpath="
+ imgpath);
LoginUserItem item = new LoginUserItem();
item.setImei(imei);
item.setPhonenum(phonenum);
item.setPassword(password);
item.setImgpath(imgpath);
item.setName(name);
item.setCreate_time(MongoUtil.mongoDateTran(new Date()));
mongodb.save(item);
}
public static boolean IsUserInfoExisted(String key, String value) {
LOG.info("[RegCheck] " + key + "=" + value);
LoginUserItem item = mongodb.findOne(key, value);
if (item == null) {
return false;
} else {
return true;
}
}
}