【mongo】Java pojo方式存取mongo中的document

1. Pojo实体定义

Person.java

import org.bson.types.ObjectId;

/**
 * @author jiangjian
 */
public class Person {
    private ObjectId id;
    private String name;
    private int age;
    private Address address;

    public Person() {
    }

    public Person(String name, int age, Address address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public ObjectId getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", address=" + address +
                '}';
    }
}

Address.java

/**
 * @author jiangjian
 */
public class Address {
    private String street;
    private String city;
    private String zip;

    public Address() {
    }

    public Address(String street, String city, String zip) {
        this.street = street;
        this.city = city;
        this.zip = zip;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(final String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(final String city) {
        this.city = city;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(final String zip) {
        this.zip = zip;
    }

    @Override
    public String toString() {
        return "Address{" +
                "street='" + street + '\'' +
                ", city='" + city + '\'' +
                ", zip='" + zip + '\'' +
                '}';
    }
}

2. 测试


import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;

import java.util.Arrays;

import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.set;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

/**
 * @author jiangjian
 */
public class POJOOperationDemo {
    public static void main(String[] args) {
        //设置编码解码器
        CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().automatic(true).build()));

        //设置MongoClient配置
        MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder().codecRegistry(pojoCodecRegistry)
                .applyToClusterSettings(builder ->
                        builder.hosts(Arrays.asList(new ServerAddress("192.168.79.20", 27017))))
                .build());

        //设置数据库
        MongoDatabase testDatabase = mongoClient.getDatabase("test");

        //设置collection名称
        MongoCollection personColl = testDatabase.getCollection("people", Person.class);

        //清空
        personColl.drop();

        //保存一个新的记录
        Person ada = new Person("jiangjian", 20, new Address("St James Square", "London", "W1"));
        personColl.insertOne(ada);

        //查询
        Person foundedPerson = personColl.find(and(eq("name", "jiangjian"), eq("age", 20))).first();
        System.out.println(foundedPerson);

        //更新
        System.out.println(personColl.updateOne(eq("name", "jiangjian"), set("age", 21)));

        //查询结果
        System.out.println(personColl.find(eq("name", "jiangjian")).first());

        personColl.deleteOne(eq("name", "jiangjian"));

        System.out.println("删除后,剩余数量为: " + personColl.countDocuments());

        mongoClient.close();

    }
}

执行效果:

[INFO][2018-09-12 18:49:32.340] Cluster created with settings {hosts=[192.168.79.20:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} 
    [INFO][2018-09-12 18:49:32.394] Cluster description not yet available. Waiting for 30000 ms before timing out 
    [INFO][2018-09-12 18:49:32.419] Opened connection [connectionId{localValue:1, serverValue:57}] to 192.168.79.20:27017 
    [INFO][2018-09-12 18:49:32.423] Monitor thread successfully connected to server with description ServerDescription{address=192.168.79.20:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 2]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2578696} 
    [INFO][2018-09-12 18:49:32.434] Opened connection [connectionId{localValue:2, serverValue:58}] to 192.168.79.20:27017 
    Person{id=5b98ef3ddafd8d42e1b31877, name='jiangjian', age=20, address=Address{street='St James Square', city='London', zip='W1'}}
AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}
Person{id=5b98ef3ddafd8d42e1b31877, name='jiangjian', age=21, address=Address{street='St James Square', city='London', zip='W1'}}
删除后,剩余数量为: 0
[INFO][2018-09-12 18:49:32.525] Closed connection [connectionId{localValue:2, serverValue:58}] to 192.168.79.20:27017 because the pool has been closed. 

你可能感兴趣的:(mongo)