java操作mongodb总结

新需求需要用到Mongodb去存APP过来的数据,所以就简单学了一下。
项目是用Spring搭建的,本来直接用spring-data-mongodb这个模块就很简单地实现操作mongodb的功能,但是,经理硬是不让,必须使用mongodb原生的驱动去实现。给我挖坑。。。

一、mongodb介绍
说来mongodb和redis很像,非常像,内存数据库,只是redis是以key-value形式存储数据的,而mongodb可以像关系型数据库一样,建立数据库,建表(mongodb叫做集合),然后往表中插入一条一条数据(mongodb叫做插入文档),这个是mongodb的基本概念。具体的百度一堆,不再赘述。

二、Java操作mongodb
首先假如mongodb的java驱动包

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.4.2</version>
</dependency>

接下来写工具类,这里注意,网上使用java操作mongodb的工具类写法很多,绝大多数是使用mongo包下面的一些类,如DB、DBObject等,但是官方是推荐我们使用mongo/client包下面的类,如MongoClient,MongoCollection,MongoDatabase,Document等

首先说一下MongoClient,mongodb客户端,本质其实就是一个数据库连接池。这里一定要注意,网上很多地方说,数据库连接用完需要关闭,但是绝对不是将MongoClient.close()掉,把整个连接池都关闭,在并发环境下,影响可想而知,这里我被深深的坑过。

MongoCollection,代表一个mongodb集合,也就是我们通常讲的表。

MongoDatabase,数据库,我们获取数据连接时,需要事先指定是哪一个数据库。

Document,文档,代表我们通常说的一条数据,注意,Mongodb数据是通过Bson格式存储的,其实也是Json格式的变种。
说道Document,我们使用mongodb的原生驱动去操作时,最大的问题,也是最核心的东西,就是Document和Java Object之间的转换。为什么网上说的很多工具类不推荐使用,那些工具类写了等于白写,比如,insert方法,直接传递一个Document方法,而Object如何转成Document却不说,当然,也有很多写了这样的转换工具类,但是依然存在很多问题。

1、工具类写法1

public  void insert(String collName,Object bean) throws JsonProcessingException {
     String json = jsonMapper.writeValueAsString(bean);
     Document doc = Document.parse(json);
     MongoCollection<Document> coll = getCollection(collName);
     coll.insertOne(doc);
 }

原理就是,将一切对象变成Json,再转成Document,简单,粗暴。但是很快就发现问题,日期类型,也就是Date类型数据,通过这样的方式存进去之后变成了时间戳。要知道,mongodb里面是有Date类型的,却被强制转换成时间戳,不明了。
当时,如果可以接受上面的形式,也行,但是,当你需要将这个长整型的数据,取出,变成Date()类型的时候,java虚拟机表示不答应了,做不到,没有办法转成date类型的数据,也正式因为这个原因,果断放弃。

2、工具类写法2
使用的mongo包下面的类

 public DBObject findOne(String collection, DBObject query, DBObject fields) {
        return db.getCollection(collection).findOne(query, fields);
  }

将Object需要通过这样的方式变成DBObject。。。。。。。万一是我们自定义的pojo,这么写,不恶心死,放弃。

DBObject dbObject2 = new BasicDBObject("username","insert2")  
            .append("age", 18)  
            .append("address", new BasicDBObject("province","陕西").append("city", "西安"))  
            .append("favourite", dbList2);  

3、目前比较靠谱的写法。
首先,项目是Spring,所以,将工具类配成Bean,通过Spring来保证MongoClient是单例的。
准备,三个注解,通过注解,进行字段反射,达到Document和Object之间的转换,其实这就是spring-data-mongodb的原理
配置文件:

#数据库名称
mongo.dbname = ak
#密码
mongo.password = root
#用户名
mongo.username = root
#主机#端口号
mongo.domains = 192.168.100.181:27017
#一个线程变为可用的最大阻塞数
mongo.connectionsPerHost= 300
#线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值
mongo.threadsAllowedToBlockForConnectionMultiplier= 5000
#连接超时时间(毫秒
mongo.connectTimeout= 15000
#最大等待时间
mongo.maxWaitTime= 3000
#自动重连
mongo.autoConnectRetry= true
#scoket保持活动
mongo.socketKeepAlive= true
#scoket超时时间
mongo.socketTimeout=0

具体是什么意思这些配置参数,百度一下。
接下来写一个抽象的父类

/**
 * 创建一个会话实现对mongoDB的原子操作
 */
public abstract class AbstractMongoSession {
    private static MongoClient mongoClient = null;
    private Class<?> clazz;
    private MongoCollection<Document> collection;


    private  String domains;
    private  String user;
    private  String password;
    private  String database;
    private  int connectionsPerHost;
    private  int connectTimeout;
    private  int maxWaitTime;
    private  int socketTimeout;
    private  int threadsAllowedToBlockForConnectionMultiplier;

    public String getDomains() {
        return domains;
    }

    public void setDomains(String domains) {
        this.domains = domains;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public int getConnectionsPerHost() {
        return connectionsPerHost;
    }

    public void setConnectionsPerHost(int connectionsPerHost) {
        this.connectionsPerHost = connectionsPerHost;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public int getMaxWaitTime() {
        return maxWaitTime;
    }

    public void setMaxWaitTime(int maxWaitTime) {
        this.maxWaitTime = maxWaitTime;
    }

    public int getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(int socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public int getThreadsAllowedToBlockForConnectionMultiplier() {
        return threadsAllowedToBlockForConnectionMultiplier;
    }

    public void setThreadsAllowedToBlockForConnectionMultiplier(int threadsAllowedToBlockForConnectionMultiplier) {
        this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
    }

    public MongoCollection<Document> getCollection() {
        return this.collection;
    }

    public Class<?> getClazz() {
        return clazz;
    }

    private  MongoDatabase getDB(){
        return getClient().getDatabase(database);
    }

    public  MongoCollection<Document> getCollection(String collName , Class<?> clazz){
        this.clazz = clazz;
        this.collection = getDB().getCollection(collName);
        return this.collection;
    }

    //初始化客户端
    public  MongoClient getClient(){
        try {
            if(null != mongoClient){
                return mongoClient;
            }
            //组装mongo服务端地址
            final List<ServerAddress> addressLists =new ArrayList<>();
            for(String domain : domains.split(";")){
                String[] hostAndPort = domain.split(":");
                String host = hostAndPort[0];
                String port = hostAndPort[1];
                ServerAddress serverAddress = new ServerAddress(host, Integer.parseInt(port));
                addressLists.add(serverAddress);
            }

            MongoClientOptions.Builder options = new MongoClientOptions.Builder();

            options.connectionsPerHost(connectionsPerHost);// 连接池设置为300个连接,默认为100
            options.connectTimeout(connectTimeout);// 连接超时,推荐>3000毫秒
            options.maxWaitTime(maxWaitTime); //
            options.socketTimeout(socketTimeout);// 套接字超时时间,0无限制
            options.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
            options.writeConcern(WriteConcern.SAFE);//

            final MongoClientOptions op = options.build();
            //组装权限对象
            final List<MongoCredential> credentialsLists = new ArrayList<>();
            MongoCredential credential = MongoCredential.createCredential(user, database, password.toCharArray());
            credentialsLists.add(credential);

            //创建客户端
            mongoClient = new MongoClient(addressLists, credentialsLists, op);
        } catch (Exception e) {
           // logger.error("MongoDB init error",e);
        }
        return mongoClient;
    }


    /*
     * 保存
     *
     * @param:实体
     *
     * @return:void
     */
    public abstract void save(String collName ,Object obj) throws Exception;

    public abstract void saveMany(List<Object> obj) throws Exception;

    // 删除数据
    public abstract long delete(Object obj) throws Exception;

    public abstract long delete(Bson bson) throws Exception;

    // 删除数据
    public abstract long deleteMany(List<Object> objs) throws Exception;

    public abstract long deleteMany(Bson bson);

    // 修改数据
    public abstract long upate(String collName ,Bson bson, Object obj) throws Exception;

    public abstract long update(Object obj) throws Exception;

    public abstract long upateMany(Bson bson, Object obj) throws Exception;

    public abstract long upateMany(Bson bson, List<Object> objs) throws Exception;

    public abstract long upateMany(List<Object> objs) throws Exception;

    // 查询数据
    public abstract Object find(String collName ,Object obj) throws Exception;

    // 获取所有的数据
    public abstract List<Object> finds(String collName  , Class<?> clazz) throws Exception;

    // 条件查询数据
    public abstract List<Object> query(String collName ,Bson bson  , Class<?> clazz) throws Exception;

    public abstract Object queryOne(Bson bson) throws Exception;

    public abstract List<Object> query(Bson bson, Bson sort) throws Exception;

    public abstract Object queryOne(Bson bson, Bson sort) throws Exception;

    public abstract List<Object> query(Bson bson, Bson sort, int limit) throws Exception;

    public abstract List<Object> query(Bson bson, Bson sort, int limit, int skip) throws Exception;

    public abstract List<Object> query(Bson bson, Bson sort, Bson filter) throws Exception;

    public abstract Object queryOne(Bson bson, Bson sort, Bson Filter) throws Exception;

    public abstract long count();

    public abstract long count(Bson bson);


}

这个类写的不怎么好,还有优化的空间,但这里暂不考虑。
接下来是实现类

/**
 * 创建一个会话实现对mongoDB的原子操作
 */
public class MongoSession extends AbstractMongoSession {


    public MongoSession() {
    }

    /**
     * 插入数据
     * @param collName 集合名称
     * @param obj   集合对应的实体
     */
    @Override
    public void save(String collName , Object obj) throws Exception{

        this.getCollection(collName , obj.getClass()).insertOne(BsonUtil.toBson(obj));

    }

    /**
     * 删除数据,未测试
     * @param obj
     * @return
     * @throws Exception
     */
    @Override
    public long delete(Object obj) throws Exception {

        DeleteResult result = this.getCollection().deleteOne(
                BsonUtil.toBson(obj));
        long count = result.getDeletedCount();
        return count;

    }

    /**
     * 未测试
     * @param obj
     */
    @Override
    public void saveMany(List<Object> obj) throws  Exception{

        this.getCollection().insertMany(BsonUtil.toBsons(obj));


    }

    /**
     * 未测试
     * @param bson
     * @return
     * @throws Exception
     */
    @Override
    public long delete(Bson bson) throws Exception {
        DeleteResult deleteResult = this.getCollection().deleteOne(bson);
        return deleteResult.getDeletedCount();
    }

    /**
     * 未测试
     * @param objs
     * @return
     */
    @Override
    public long deleteMany(List<Object> objs) throws Exception{
        List<Document> documents;
        int count = 0;

        documents = BsonUtil.toBsons(objs);
        for (int i = 0; null != documents && i < documents.size(); i++) {
            DeleteResult deleteResult = this.getCollection().deleteOne(
                    documents.get(i));
            count += deleteResult.getDeletedCount();
        }
        return count;

    }

    /**
     * 未测试
     * @param bson
     * @return
     */
    @Override
    public long deleteMany(Bson bson) {
        DeleteResult deleteResult = this.getCollection().deleteMany(bson);
        return deleteResult.getDeletedCount();
    }

    /**
     * 更新数据
     * @param collName 集合名称
     * @param bson 条件
     * @param obj 集合对应实体
     * @return
     */
    @Override
    public long upate(String collName ,Bson bson, Object obj) throws Exception{

        UpdateResult result = this.getCollection(collName , obj.getClass()).updateOne(bson,
                new Document("$set", BsonUtil.toBson(obj)));
        return result.getMatchedCount();

    }

    /**
     * 未测试
     * @param obj
     * @return
     */
    @Override
    public long update(Object obj) throws Exception{
        Document document;

        document = BsonUtil.toBson(obj);
        Bson bson = Filters.eq("_id", document.get("_id"));
        UpdateResult updateResult = this.getCollection().updateOne(
                bson,
                new Document("$set", document));
        return updateResult.getMatchedCount();

    }

    /**
     * 未测试
     * @param bson
     * @param obj
     * @return
     */
    @Override
    public long upateMany(Bson bson, Object obj) throws Exception{

        UpdateResult updateResult = this.getCollection().updateMany(bson,
                new Document("$set", BsonUtil.toBson(obj)));
        return updateResult.getMatchedCount();

    }

    /**
     * 未测试
     * @param bson
     * @param obj
     * @return
     */
    @Override
    public long upateMany(Bson bson, List<Object> obj) throws Exception{
        for (int i = 0; null != obj && i < obj.size(); i++) {

            UpdateResult result = this.getCollection().updateMany(bson,
                    new Document("$set", BsonUtil.toBson(obj)));
            return result.getMatchedCount();

        }
        return 0;
    }

    /**
     * 未测试
     * @param objs
     * @return
     */
    @Override
    public long upateMany(List<Object> objs) throws Exception{
        long count = 0;
        for (int i = 0; null != objs && i < objs.size(); i++) {

            UpdateResult result = this.getCollection().updateMany(
                    Filters.eq("_id",
                            BsonUtil.toBson(objs.get(i)).get("_id")),
                    new Document("$set", BsonUtil.toBson(objs.get(i))));
            count += result.getMatchedCount();

        }
        return count;
    }

    /**
     *  按_id查询
     * @param collName
     * @param obj
     * @return
     */
    @Override
    public Object find(String collName ,Object obj) throws Exception{

        Bson bson = Filters.eq("_id", new ObjectId(BsonUtil.toBson(obj).get("_id").toString()));
        Document document = this.getCollection(collName , obj.getClass())
                .find(bson)
                .first();
        return BsonUtil.toBean(document, this.getClazz());
    }

    /**
     * 查询所有 , 未测试
     * @return
     */
    @Override
    public List<Object> finds(String collName , Class<?> clazz) throws Exception{
        FindIterable<Document> doIterable = this.getCollection(collName, clazz).find();
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();

            objects.add(BsonUtil.toBean(document, this.getClazz()));

        }
        return objects;
    }

    /**
     * 按条件查询
     * @param collName
     * @param bson
     * @param clazz
     * @return
     */
    @Override
    public List<Object> query(String collName , Bson bson , Class<?> clazz) throws Exception{
        FindIterable<Document> doIterable = this.getCollection(collName , clazz).find(bson);
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            objects.add(BsonUtil.toBean(document, this.getClazz()));
        }
        return objects;
    }

    @Override
    public Object queryOne(Bson bson) throws Exception{
        Document document = this.getCollection().find(bson).first();

        return BsonUtil.toBean(document, this.getClazz());

    }

    @Override
    public List<Object> query(Bson bson, Bson sort) throws Exception{
        FindIterable<Document> doIterable = this.getCollection().find(bson)
                .sort(sort);
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            objects.add(BsonUtil.toBean(document, this.getClazz()));
        }
        return objects;
    }

    @Override
    public Object queryOne(Bson bson, Bson sort) throws Exception{
        Document document = this.getCollection().find(bson).sort(sort).first();

        return BsonUtil.toBean(document, this.getClazz());
    }

    @Override
    public List<Object> query(Bson bson, Bson sort, int limit) throws Exception{
        FindIterable<Document> doIterable = this.getCollection().find(bson)
                .sort(sort);
        if (limit > 0) {
            doIterable = doIterable.limit(limit);
        }
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            objects.add(BsonUtil.toBean(document, this.getClazz()));
        }
        return objects;
    }

    @Override
    public List<Object> query(Bson bson, Bson sort, int limit, int skip) throws Exception{
        FindIterable<Document> doIterable = this.getCollection().find(bson)
                .sort(sort);
        if (limit > 0) {
            doIterable = doIterable.limit(limit);
        }
        if (skip > 0) {
            doIterable = doIterable.skip(skip);
        }
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            objects.add(BsonUtil.toBean(document, this.getClazz()));
        }
        return objects;
    }

    @Override
    public List<Object> query(Bson bson, Bson sort, Bson filter) throws Exception{
        FindIterable<Document> doIterable = this.getCollection().find(bson)
                .sort(sort).filter(filter);
        MongoCursor<Document> cursor = doIterable.iterator();
        List<Object> objects = new ArrayList<Object>();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            objects.add(BsonUtil.toBean(document, this.getClazz()));
        }
        return objects;
    }

    @Override
    public Object queryOne(Bson bson, Bson sort, Bson Filter) throws Exception{
        Document document = this.getCollection().find(bson).sort(sort)
                .filter(Filter).first();

        return BsonUtil.toBean(document, this.getClazz());

    }

    @Override
    public long count() {

        return this.getCollection().count();
    }

    @Override
    public long count(Bson bson) {
        // TODO Auto-generated method stub
        return this.getCollection().count(bson);
    }
}

当中有一些方法没有用到,所以没有做测试,可能存在问题。但也只是微调就可以了,比如将getCollection(),换成传参数的那个getCollention。

注意到里面有一个BsonUtil工具类,里面就是实现Object和Document转换的方法
在次之前,需要准备三个注解。分别代表,集合,列。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    public String name();

    public String text() default "表格映射";
}


@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    public String name();

    public String text() default "这是一个属性映射";
}


@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotColumn {
    public String text() default "不是属性字段";
}

BenUtil工具类

/**
    工具类

**/
public class BsonUtil {
    public static <T> List<T> toBeans(List<Document> documents, Class<T> clazz)
            throws IllegalArgumentException, InstantiationException,
            IllegalAccessException, InvocationTargetException {
        List<T> list = new ArrayList<T>();
        for (int i = 0; null != documents && i < documents.size(); i++) {
            list.add(toBean(documents.get(i), clazz));
        }
        return list;
    }

    /*
     * 将Bson 转化为对象
     *
     * @param:Bson文档
     *
     * @param:类pojo
     *
     * @param:返回对象
     */
    public static <T> T toBean(Document document, Class<T> clazz)
            throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        T obj = clazz.newInstance();// 声明一个对象
        Field[] fields = clazz.getDeclaredFields();// 获取所有属性
        Method[] methods = clazz.getMethods();// 获取所有的方法
        /*
         * 查找所有的属性,并通过属性名和数据库字段名通过相等映射
         */
        for (int i = 0; i < fields.length; i++) {
            String fieldName = fields[i].getName();
            Column column = fields[i].getAnnotation(Column.class);
            Object bson = null;
            if (null != column && null != column.name()) {
                bson = document.get(column.name());
            } else if ("id".equals(fieldName)) {
                bson = document.get("_id");
            } else {
                bson = document.get(fieldName);
            }
            if (null == bson) {
                continue;
            } else if (bson instanceof Document) {// 如果字段是文档了递归调用
                bson = toBean((Document) bson, fields[i].getType());
            } else if (bson instanceof MongoCollection) {// 如果字段是文档集了调用colTOList方法

                bson = colToList(bson, fields[i]);
            }
            for (int j = 0; j < methods.length; j++) {// 为对象赋值
                String metdName = methods[j].getName();
                if (equalFieldAndSet(fieldName, metdName)) {
                    methods[j].invoke(obj, bson);
                    break;
                }
            }
        }
        return obj;
    }

    public static List<Document> toBsons(List<Object> objs)
            throws IllegalArgumentException, SecurityException,
            IllegalAccessException, InvocationTargetException,
            NoSuchFieldException {
        List<Document> documents = new ArrayList<Document>();
        for (int i = 0; null != objs && i < objs.size(); i++) {
            documents.add(toBson(objs.get(i)));
        }
        return documents;
    }

    /*
     * 将对象转化为Bson文档
     *
     * @param:对象
     *
     * @param:类型
     *
     * @return:文档
     */
    public static Document toBson(Object obj) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            SecurityException, NoSuchFieldException {
        if (null == obj) {
            return null;
        }
        Class<? extends Object> clazz = obj.getClass();
        Document document = new Document();
        Method[] methods = clazz.getDeclaredMethods();
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; null != fields && i < fields.length; i++) {
            Column column = fields[i].getAnnotation(Column.class);// 获取列注解内容
            NotColumn notColumn = fields[i].getAnnotation(NotColumn.class);// 获取否列
            String key = null;// 对应的文档键值
            if (null != column && null != column.name()) {// 存在列映射取值
                key = column.name();
            } else if (null != notColumn) {// 不是列的情况
                continue;
            } else {
                key = fields[i].getName();// 默认情况通过属性名映射
                if ("id".equals(key)) {// 替换id为_id
                    key = "_id";
                }
            }
            String fieldName = fields[i].getName();
            /*
             * 获取对象属性值并映射到Document中
             */
            for (int j = 0; null != methods && j < methods.length; j++) {
                String methdName = methods[j].getName();
                if (null != fieldName && equalFieldAndGet(fieldName, methdName)) {
                    Object val = methods[j].invoke(obj);// 得到值
                    if (null == val) {
                        continue;
                    }
                    if (isJavaClass(methods[j].getReturnType())) {
                        if (methods[j].getReturnType().getName()
                                .equals("java.util.List")) {// 列表处理
                            @SuppressWarnings("unchecked")
                            List<Object> list = (List<Object>) val;
                            List<Document> documents = new ArrayList<Document>();
                            for (Object obj1 : list) {
                                documents.add(toBson(obj1));
                            }
                            document.append(key, documents);
                        } else {// 其它对象处理,基本类型
                            document.append(key, val);
                        }
                    } else {// 自定义类型
                        document.append(key, toBson(val));
                    }
                }
            }
        }
        return document;
    }

    /*
     * 是否是自定义类型】
     *
     * false:是自定义
     */
    private static boolean isJavaClass(Class<?> clz) {
        return clz != null && clz.getClassLoader() == null;
    }

    /*
     * 将文档集转化为列表
     *
     * @param:文档集
     *
     * @param:属性类型
     *
     * @return:返回列表
     */
    private static List<Object> colToList(Object bson, Field field)
            throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        ParameterizedType pt = (ParameterizedType) field.getGenericType();// 获取列表的类型
        List<Object> objs = new ArrayList<Object>();
        @SuppressWarnings("unchecked")
        MongoCollection<Document> cols = (MongoCollection<Document>) bson;
        MongoCursor<Document> cursor = cols.find().iterator();
        while (cursor.hasNext()) {
            Document child = cursor.next();
            @SuppressWarnings("rawtypes")
            Class clz = (Class) pt.getActualTypeArguments()[0];// 获取元素类型
            @SuppressWarnings("unchecked")
            Object obj = toBean(child, clz);
            System.out.println(child);
            objs.add(obj);

        }
        return objs;
    }

    /*
     * 比较setter方法和属性相等
     */
    private static boolean equalFieldAndSet(String field, String name) {
        if (name.toLowerCase().matches("set" + field.toLowerCase())) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 比较getter方法和属性相等
     */
    private static boolean equalFieldAndGet(String field, String name) {
        if (name.toLowerCase().matches("get" + field.toLowerCase())) {
            return true;
        } else {
            return false;
        }
    }
}

到此,工具类大功告成。

4、使用方式
实体类

@Table(name = "GPSPOINT")
public class GPSPoint{


    /**
     * mongo id
     */
    @Column(name = "_id")
    private String _id;
    /**
     * 员工ID
     */
    @Column(name = "empId")
    private int empId;

    /**
     * 设备类型
     */
    @Column(name = "deviceType")
    private int deviceType;

    /**
     * 高德GPS
     */
    @Column(name = "gdGps")
    private Point gdGps;

    /**
     * 百度GPS
     */
    @Column(name = "bdGps")
    private Point bdGps;

    /**
     * 时间
     */
    @Column(name = "time")
    private Date time;

    /**
     * 
     */
    @Column(name = "dealFlag")
    private int dealFlag;

    /**
     * 
     */
    @Column(name = "state")
    private int state;
//getset方法省略
}

实体类中,@Table注解指定了,这个实体对应的是mongodb中的那个表(集合),@Column表明这个字段是一个mongodb的字段,在BeanUtil工具类中,mongodb的字段和Object字段之间的映射关系就是通过这个注解实现,看代码就能看出来。

接下来,就是在Spring中配置一个bean

    <bean id="mongoSession" class="com.common.mongodb.MongoSession">
        <property name="domains" >
            <value>${mongo.domains}</value>
        </property>
        <property name="user">
            <value>${mongo.username}</value>
        </property>
        <property name="password">
            <value>${mongo.password}</value>
        </property>
        <property name="database">
            <value>${mongo.dbname}</value>
        </property>
        <property name="connectionsPerHost" value="${mongo.connectionsPerHost}"></property>
        <property name="connectTimeout" value="${mongo.connectTimeout}"></property>
        <property name="maxWaitTime" value="${mongo.maxWaitTime}"></property>
        <property name="socketTimeout" value="${mongo.socketTimeout}"></property>
        <property name="threadsAllowedToBlockForConnectionMultiplier" value="${mongo.threadsAllowedToBlockForConnectionMultiplier}"></property>
    </bean>

测试类就很简单了

@Resource
private MongoSession mongoSession;

 @Test
 public void handl(){
        GPSPoint pointBo = new GPSPoint();
        pointBo.setEmpId(54321);
        pointBo.setDeviceType(0);
        pointBo.setGdGps(new Point("130.336122,140.118414"));
        pointBo.setDealFlag(1);
        pointBo.setState(1);
        pointBo.setTime(new Date());
        //插入
        mongoSession.save(pointBo);

        //更新
         Bson bson = Filters.eq("_id" , new ObjectId("58fec5b300300200f01cf9ab"));
         System.out.println(mongoSession.upate("GPSPoint" , bson , pointBo));


    //查询
     Bson bson = Filters.eq("dealFlag" , 0);
      System.out.println(mongoSession.query(bson));
 }

总结
这个工具类,虽然也有缺陷,比较繁琐,但是,使用起来比较方便。

注意
字段不要用枚举类型,目前,我还没看见有如果处理枚举类型的文章,spring-data-mongodb当前版本也不支持处理枚举类型,还是用简单类型存放吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值