您的位置:首页 > 数据库 > Mongodb

Mongodb自己封装的工具类

2016-12-13 08:51 417 查看

如何开启链接

链接本地的monogdb数据库

MongoClient client = new MongoClient("localhost",27017);

 

获取为itcast的数据库对象

MongoDatabase db =client.getDatabase("itcast");

 

从数据库中获取为itcast的文档对象

MongoCollection<Document>collection =  db.getCollection("itcast");

 

 

Mongdb中的CURD操作

注意这些操作都是针对文档对象,就类型域mysql中的表

查询所有

获取查询的所有文档迭代对象

FindIterable<Document> it = collection.find();
 
获取所有文档对象的油标对象
      MongoCursor<Document> cursor = it.iterator();
 
    对获取的油标遍历并获取文档对象
       while(cursor.hasNext()){
          Document doc =cursor.next();
          String name=doc.getString("name");
          Double age =doc.getDouble("age");
          ObjectId id =doc.getObjectId("_id");
          System.out.println(name+":"+age+":"+id);
       }
   
   关闭资源

       cursor.close();
       client.close();

 

 

 

指定查询

这类似域 10<age<23

BasicDBObject filter =new  BasicDBObject("age",new BasicDBObject("$gt",10).append("$lt",
23));
 
这类似与and name =‘yinchong’
filter.append("name",
"yinchong");
 
执行条件查询
FindIterable<Document>it = collection.find(filter);
 
遍历结果  
MongoCursor<Document>cursor = it.iterator();
 while(cursor.hasNext()){
            Document doc = cursor.next();
            String name = doc.getString("name");
            Double age = doc.getDouble("age");
            ObjectId id = doc.getObjectId("_id");
            System.out.println(name+": "+age+": "+id);
       }
 
关闭资源
cursor.close();
client.close();
 

插入数据

这句类似插入json对象为

  {

  name:’冲冲’,

   age:20,

    bobby:{

       grily:’翠翠’,

       game:’lol’,

}



解释:

 这里的插入其实利用map来实现。就好比如所你要插入的bean中含用bean是你需要再创建一个map来存放那个对象再把这个map放入到上一个map中

Map<String,Object>map = new HashMap<String,Object>();
       map.put("name",
"冲冲");
       map.put("age", 24);
       map.put("gender",
"男");
       Map<String,Object> hobby = newHashMap<String,Object>();
       hobby.put("grily",
"翠翠");
       hobby.put("game",
"lol");
       map.put("hobby", hobby);
 
        生成一个文档对象
       Document doc = new Document(map);
 
        插入进去
       collection.insertOne(doc);
        client.close();

 

删除数据

Bson filter =new BasicDBObject("_id",new ObjectId("584961d9fbdb38f43018ecbb"));
      
collection.deleteOne(filter);
client.close();

 

 

 

更新数据

对于更新数据推荐使用ObjectId来实现

Bson filter = new BasicDBObject("_id",new ObjectId("584961e8fbdb38f43018ecbc"));
 
把要更新的数据采用map存放然后利用构造方法生产BasicDBObject对象
Map<String,Object>map = new HashMap<String,Object>();
map.put("name",
"张玉洁");
map.put("age", 20);
Bson update = newBasicDBObject(map);
 
更新的条件和更新的数据   
collect.updateOne(filter,new BasicDBObject("$set",update));
client.close();

 

总结:Monogodb最大的特点就是操作文档,它的数据变相的在使用map原因很简单它的存储是json格式的使用map可以很好的表现出来

 

几个重要的类:

Document:注意不是w3c的jar包(文档对象一起以它为中心)

BasicDBObject:常用的方法append

常用的构造方法:

 BasicDBObject(Map<String,Object>map)

 BasicDBObject(String , Object )

 

 

 

一: Insert操作

     上一篇也说过,文档是采用“K-V”格式存储的,如果大家对JSON比较熟悉的话,我相信学mongodb是手到擒来,我们知道JSON里面Value

可能是“字符串”,可能是“数组”,又有可能是内嵌的一个JSON对象,相同的方式也适合于BSON。

      常见的插入操作也就两种形式存在:“单条插入”和“批量插入”。

   

    ①  单条插入

         先前也说了,mongo命令打开的是一个javascript shell。所以js的语法在这里面都行得通,看起来是不是很牛X。     

public class MongoDBUtils {

private static MongoClient client;
private static MongoDatabase db;
private static MongoCollection<Document> collection;

// 将查询的数据设置到bean上
public static <T> List<T> data2Bean(Class<T> clazz,
MongoCursor<Document> cursor) {
try {

List<T> array = new LinkedList<T>();
while (cursor.hasNext()) {
Document doc = cursor.next();
T bean = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
if (fields != null) {
for (Field field : fields) {
field.setAccessible(true);

                        setData(bean, field, doc);
}
array.add(bean);
}

}

return array;

} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (cursor != null) {
cursor.close();
}
}
}

//传入bean返回Document进行插入
public static<T> Document transform2Doc(T bean) throws Exception{
Class clazz = bean.getClass();
HashMap<String,Object> data = new HashMap<String,Object>();
Field[] fields = clazz.getDeclaredFields();
if(fields!=null){
for(Field field:fields){
field.setAccessible(true);
String fname = field.getName();
if(fname.equals("id"))
continue;
Object value = field.get(bean);
data.put(fname, value);
}
}
return new Document(data);
}

/**
* 开启链接
* @param address
* @param port
*/
public static void openClient(String address,int port){
 if(client!=null){
 client.close();
 client = null;
 }
client = new MongoClient(address,port);
}

/**
* 打开数据库链接池
* @param dbName
*/
public static void openDatabase(String dbName){
if(client==null)
throw new RuntimeException("请先开启链接,先调用openClient");
db = client.getDatabase(dbName);
}

/**
* 开启数据库链接包括开启
* @param address
* @param port
* @param dbName
*/
public static void openAll(String address,int port,String dbName,String colName){
if(client==null)
client = new MongoClient(address,port);
if(db==null)
db = client.getDatabase(dbName);
if(collection==null)
collection = db.getCollection(colName);
}

/**
* 插入一条数据
* @param bean
*/
public static<T>  void  insertOne(T bean){
try {
collection.insertOne(transform2Doc(bean));
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 修改一条数据
* @throws IllegalAccessException 
* @throws IllegalArgumentException 
*/
public static<T> void update(Map<String,Object> condition,T bean) throws Exception{
BasicDBObject filter = new BasicDBObject();
Set<String> keys = condition.keySet();
for(String key:keys){
if(key.equals("id")){
filter.append("_id", new ObjectId(condition.get(key)+""));
continue;
}
filter.append(key, condition.get(key));
}
Map<String,Object> newData = new HashMap<String,Object>();
Class clazz = bean.getClass();
//便利获取所有的字段并将不为空的数据保存到map中
   Field[] fields = clazz.getDeclaredFields();
   for(Field field:fields){
    field.setAccessible(true);
    Object tv = field.get(bean);
    if(tv==null)
    continue;
    newData.put(field.getName(), tv);
   }

Bson update = new BasicDBObject(newData);
collection.updateMany(filter,new BasicDBObject("$set", update) );

}

/**
* 删除数据
*/
public static void delete(Map<String,Object> condition){
BasicDBObject filter = new BasicDBObject();
Set<String> keys = condition.keySet();
for(String key:keys){
if(key.equals("id")){
filter.append("_id", new ObjectId(condition.get(key)+""));
continue;
}
filter.append(key, condition.get(key));
}
collection.deleteMany(filter);
}

/**
* 查询所有数据
*/
public static<T> List<T> findAll(Class clazz){
FindIterable<Document> it = collection.find();
MongoCursor<Document> cursor = it.iterator();
return data2Bean(clazz, cursor);
}

/**
* 查询指定数据
*/
public static<T> List<T> findCondition(Map<String,Object> condition,Class clazz){
BasicDBObject filter = new BasicDBObject();
Set<String> keys = condition.keySet();
for(String key:keys){
if(key.equals("id")){
filter.append("_id", new ObjectId(condition.get(key)+""));
continue;
}
filter.append(key, condition.get(key));
}
FindIterable<Document> it = collection.find(filter);
MongoCursor<Document> cursor = it.iterator();
return data2Bean(clazz, cursor);
}

public static void  close(){
if(client!=null){
client.close();
client=null;
}
}

private static <T> void setData(T bean,Field field,Document doc) throws Exception{
String type = field.getType().getSimpleName();
String name = field.getName();
if("String".equals(type)&&"id".equals(name)){
ObjectId id = doc.getObjectId("_id");
String data = id.toString();
field.set(bean, data);
}else if("Double".equals(type)){
Double data = doc.getDouble(name);
field.set(bean, data);
}else if("String".equals(type)){
String data = doc.getString(name);
field.set(bean, data);
}else if("Date".equals(type)){
Date data = doc.getDate(name);
field.set(bean,data);
}else if("Boolean".equals(type)){
Boolean data = doc.getBoolean(name);
field.set(bean, data);
}else if("Integer".equals(type)){
String value = null;
try{
value = doc.getDouble(name)+"";
}catch(ClassCastException e){
value = doc.getInteger(name)+"";
}
int index = value.lastIndexOf(".");
if(index>-1)
value = value.substring(0,index);
Integer data = Integer.parseInt(value);
field.set(bean, data);
}else if("Long".equals(type)){
String value = null;
try{
value = doc.getDouble(name)+"";
}catch(ClassCastException e){
value = doc.getLong(name)+"";
}
int index = value.lastIndexOf(".");
if(index>-1)
value = value.substring(0,index);
Long data = Long.parseLong(value);
field.set(bean,data);
}else if("Float".equals(type)){
Float data =Float.parseFloat(doc.getDouble(name)+"");
field.set(bean, data);
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: