• MongoDb二


    获取集合的时候,可以传入bean的class文件。来实现数据的绑定。
    在这之前。需要自定义一个Codec类。进行数据的转换。

    MongoClient client=new MongoClient(new ServerAddress("127.0.0.1",27017)); MongoDatabase db= client.getDatabase("chaoba"); CodecRegistry codecRegistry=CodecRegistries.fromRegistries(CodecRegistries.fromCodecs(new Chaoba1Codec())); MongoCollection<Chaoba1> chaoba1 =db.getCollection("chaoba1",Chaoba1.class).withCodecRegistry(codecRegistry); // MongoCursor<Chaoba1> result=chaoba.find().iterator(); // while(result.hasNext()) { // System.out.println(result.next()); // } Chaoba1 chaoba =new Chaoba1(); chaoba.setName("Demo2"); chaoba1.insertOne(chaoba);

    Codec类

    package demo2;
    
    import org.bson.BsonReader;
    import org.bson.BsonWriter;
    import org.bson.codecs.Codec;
    import org.bson.codecs.DecoderContext;
    import org.bson.codecs.EncoderContext;
    
    public class Chaoba1Codec implements Codec<Chaoba1>{
    
        @Override
        public void encode(BsonWriter writer, Chaoba1 value, EncoderContext encoderContext) {
            // TODO Auto-generated method stub
            writer.writeStartDocument();
            writer.writeString("name", value.getName());
    //        writer.writeString("sex", value.getSex());
            writer.writeEndDocument();
        }
    
        @Override
        public Class<Chaoba1> getEncoderClass() {
            // TODO Auto-generated method stub
            return Chaoba1.class;
        }
    
        @Override
        public Chaoba1 decode(BsonReader reader, DecoderContext decoderContext) {
            // TODO Auto-generated method stub
            reader.readStartDocument();
            
            
            Chaoba1 chaoba1=new Chaoba1();
            
            chaoba1.set_id(reader.readObjectId("_id"));
            chaoba1.setName(reader.readString("name"));
    //        chaoba1.setSex(reader.readString("sex"));
            reader.readEndDocument();
            return chaoba1;
        }
    
    }
    一万年太久,只争朝夕!
  • 相关阅读:
    12. nc/netcat 用法举例
    7. 由一道ctf学习变量覆盖漏洞
    11. 几点基于Web日志的Webshell检测思路
    约瑟夫环
    栈结构的经典算法题
    二叉查找树之二
    fork与vfork
    数组常见算法题
    赛马问题
    fibonacci 数列及其应用
  • 原文地址:https://www.cnblogs.com/chaoba/p/10057650.html
Copyright © 2020-2023  润新知