MongoDb学习三(spring-data-mongodb)

本文采用2个种配置方式、xml配置  代码配置方式进行数据库的连接。
实现简单的增删该查等一些操作。代码都有注释

官方文档如下
https://docs.spring.io/spring-data/mongodb/docs/2.1.3.RELEASE/reference/html/

具体代码如下
pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringMogo</groupId> <artifactId>chaoba</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>chaoba</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>2.1.3.RELEASE</version> </dependency> </dependencies> </project>

xml配置文件spring.xml 存放到资源文件夹即可

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:mongo="http://www.springframework.org/schema/data/mongo"
          xsi:schemaLocation=
          "http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Default bean name is 'mongo' -->
    <mongo:mongo-client host="localhost" port="27017" id="mongo"/>
<mongo:db-factory dbname="chaoba" mongo-ref="mongo"/>

<bean id="MongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
  </bean>
</beans>
文章实体类
package document;

import java.util.Date;
import java.util.List;

import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection="artcle_info")
public class Artcle {
    @Id()
    private String id;
    @Field("title")
    private String title;
    @Field("content")
    private String content;
    @Field("tags")
    private List<String> tags;
    @Field("time")
    private Date addTIme;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public List<String> getTags() {
        return tags;
    }
    public void setTags(List<String> tags) {
        this.tags = tags;
    }
    public Date getAddTIme() {
        return addTIme;
    }
    public void setAddTIme(Date addTIme) {
        this.addTIme = addTIme;
    }
    

}
主要代码。增删改查
package SpringMogo.chaoba;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import document.Artcle;

/**
 * Hello world!
 *
 */
public class App {
    /*
     * 通过xml配置文件获取mongotemp
     */
    private static MongoTemplate mongoTemp;
    static {
        mongoTemp = (MongoTemplate) new ClassPathXmlApplicationContext("classpath:spring.xml").getBean("MongoTemplate");
    }

    public static void main(String[] args) {

        // insertArtcle();
        // mongoTemp.getCollectionNames().forEach(System.out::println);
        // updateArtcle();
        // del();
    }

    /*
     * 插入。需要吧Document存入list
     */
    private static void insertArtcle() {
        List<Artcle> list = new ArrayList();
        Artcle a = new Artcle();
        a.setTitle("暮雪超霸");
        a.setAddTIme(new Date());
        a.setTags(Arrays.asList("帅哥", "最帅"));
        a.setContent("暮雪超霸是一个小帅哥");
        list.add(a);
        mongoTemp.insert(list, Artcle.class);
    }

    /*
     * 修改 修改有多个重载方法。可以指定clas或者指定集合名称、。如果使用集合名称。key就是集合key 如果是clas。写实体名
     */
    private static void updateArtcle() {
        // 这种方法。如果查询条件不存在。不修改,不插入
        mongoTemp.updateFirst(Query.query(new Criteria("title").is("暮雪超霸")), Update.update("content", "暮雪超霸是最帅的小哥哥"),
                Artcle.class);

        // 查询条件如果不存在,。插入数据
        mongoTemp.upsert(Query.query(new Criteria("title").is("暮雪超霸111")), Update.update("content", "暮雪超霸是最帅的小哥哥"),
                Artcle.class);

        // 删除指定的key
        mongoTemp.updateFirst(Query.query(new Criteria("title").is("暮雪超霸")), new Update().unset("title"), Artcle.class);

        // 删除数据。不返回数据
        mongoTemp.remove(Query.query(Criteria.where("title").is("暮雪超霸")), Artcle.class);

        // 删除一条并返回数据
        Artcle resu = (Artcle) mongoTemp.findAndRemove(Query.query(Criteria.where("title").is("暮雪超霸111")),
                Artcle.class);
        System.out.println(resu.getTitle());
        // 删除多条;并返回数据
        List<Artcle> list = mongoTemp.findAllAndRemove(Query.query(Criteria.where("title").is("暮雪超霸111")),
                Artcle.class);

    }

    private static void del() {
        // 删除数据。不返回数据
        mongoTemp.remove(Query.query(Criteria.where("title").is("暮雪超霸")), Artcle.class);

        // 删除一条并返回数据
        Artcle resu = (Artcle) mongoTemp.findAndRemove(Query.query(Criteria.where("title").is("暮雪超霸111")),
                Artcle.class);
        System.out.println(resu.getTitle());
        // 删除多条;并返回数据
        List<Artcle> list = mongoTemp.findAllAndRemove(Query.query(Criteria.where("title").is("暮雪超霸111")),
                Artcle.class);
        // 删除集合
        mongoTemp.dropCollection(Artcle.class);

        // 删除库
        mongoTemp.getDb().drop();
    }

    private static void select() {
        // 带条件查询
        List<Artcle> list = mongoTemp.find(Query.query(Criteria.where("title").is("暮雪超霸")), Artcle.class);

        // 查询所有
        List<Artcle> list1 = mongoTemp.findAll(Artcle.class);

        // 查询个数
        long count = mongoTemp.count(Query.query(Criteria.where("title").is("暮雪超霸")), Artcle.class);

        // 查询一个
        Artcle artcle = mongoTemp.findOne(Query.query(Criteria.where("title").is("暮雪超霸")), Artcle.class);

        // id查询
        artcle = mongoTemp.findById(new ObjectId("5c04b4af4a24a32b24d8078c"), Artcle.class);

        // 分页查询 如果在大量数据下。先排序,然后记录上次最后一条数据id,如果大于上次id。limit 页数
        list = mongoTemp.find(Query.query(Criteria.where("title").is("暮雪超霸")).skip(0).limit(10), Artcle.class);

        // in查询 还有and 大于小于 等方法
        list1 = mongoTemp.find(Query.query(Criteria.where("title").in("暮雪超霸", "暮雪超霸1")), Artcle.class);
        list1 = mongoTemp.find(Query.query(Criteria.where("title").orOperator(Criteria.where("title").is("暮雪超霸"))),
                Artcle.class);

        // or查询
        list1 = mongoTemp.find(Query.query(
                new Criteria().orOperator(Criteria.where("title").is("暮雪超霸"), Criteria.where("title").is("暮雪超霸1"))),
                Artcle.class);

    }
}
代码连接
package document;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class MongoDbCodeContent {
    /*
     * 代码方式连接
     */

    public static void main(String[] args) {

        MongoClient client = new MongoClient(new ServerAddress("127.0.0.1", 27017));

        MongoTemplate mongoTemplate = new MongoTemplate(new SimpleMongoDbFactory(client, "chaoba"));
        mongoTemplate.getCollectionNames().forEach(System.out::println);

    }

}

 

posted @ 2018-12-03 15:09  暮雪超霸  阅读(927)  评论(0编辑  收藏  举报