简单的spring-data集成mongoDB项目,实现crud的功能

集成了spring框架的jar,加上三个spring-data的jar和一个驱动包java

用IDE开发工具新建一个java 项目,须要spring框架的包,和spring-data须要的包,分别是spring

包下的三个包:spring-data-mongodbmongodb

,spring-data-mongodb-cross-store,spring-data-mongodb-log4j。数据库

以及mongoDB数据库的驱动包mongo-2.8.0.jar,也须要commons-logging-1.0.4和log4j-1.2.17.jar包,若是还缺乏什么包,更加报错添加便可express

项目须要的目录结构:app

每一个类中完整的代码贴出以下:框架

实体类:ide

这里也解释一下代码注解函数

<!--解释开始-->工具

spring-data-mongodb中的实体映射是经过

MongoMappingConverter这个类实现的。它能够经过注释把

java类转换为mongodb的文档。
它有如下几种注释:
@Id - 文档的惟一标识,在mongodb中为ObjectId,它是惟一的,经过时间戳+机器标识+进程ID+自增计数器(确保同一秒内产生的Id不会冲突)构成。

@Document - 把一个java类声明为mongodb的文档,能够通

过collection参数指定这个类对应的文档。

@DBRef - 声明相似于关系数据库的关联关系。

@Indexed - 声明该字段须要索引,建索引能够大大的提升查询效率。

@CompoundIndex - 复合索引的声明,建复合索引能够有效地提升多字段的查询效率。

@GeoSpatialIndexed - 声明该字段为地理信息的索引。

@Transient - 映射忽略的字段,该字段不会保存到

mongodb。

@PersistenceConstructor - 声明构造函数,做用是把从数据库取出的数据实例化为对象。该构造函数传入的值为从DBObject中取出的数据。

<!--解释结束-->

package main.pojo;


import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Tree {
    @Id
    private String id;
    private String name;
    private String category;
    private int age;
    public Tree(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age
                + ", category=" + category + "]";
    }
}

 

链接mongodb的dao层

package main.dao;


import com.mongodb.WriteResult;


import java.util.List;


public interface Repository<T> {
    //方法接口
    public List<T> getAllObjects();


    public void saveObject(T object);


    public T getObject(String id);


    public WriteResult updateObject(String id, String name);


    public void deleteObject(String id);


    public void createCollection();


    public void dropCollection();




}

 

实现类:

package main.impl;


import com.mongodb.WriteResult;
import main.dao.Repository;
import main.pojo.Tree;
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 java.util.List;

public class RepositoryImpl implements Repository<Tree>{
    MongoTemplate mongoTemplate;


//    Repository repository;
//
//    public void setRepository(Repository repository) {
//        this.repository = repository;
//    }


    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }


    //查询
    public List<Tree> getAllObjects() {
        return mongoTemplate.findAll(Tree.class);
    }


    //增长
    public void saveObject(Tree tree) {
        mongoTemplate.insert(tree);
    }


    //查询
    public Tree getObject(String id) {
        return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),  Tree.class);
    }


    //修改
    public WriteResult updateObject(String id, String name) {
        return mongoTemplate.updateFirst(
        new Query(Criteria.where("id").is(id)),
        Update.update("name", name), Tree.class);
    }


    //删除
    public void deleteObject(String id) {
        mongoTemplate .remove(new Query(Criteria.where("id").is(id)), Tree.class);
    }


    public void createCollection() {
        if (!mongoTemplate.collectionExists(Tree.class)) {
            mongoTemplate.createCollection(Tree.class);
        }
    }


    public void dropCollection() {
        if (mongoTemplate.collectionExists(Tree.class)) {
            mongoTemplate.dropCollection(Tree.class);
        }
    }


}

 

applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd


http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">


    <bean id="Repository"
    class="main.impl.RepositoryImpl">
    <property name="mongoTemplate" ref="mongoTemplate" />
    </bean>


    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongo" ref="mongo" />
    <constructor-arg name="databaseName" value="temp" />
    </bean>


    <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
    <property name="host" value="localhost" />
    <property name="port" value="27017" />
    </bean>


    <context:annotation-config />
            <!-- Scan components for annotations within the configured package -->
    <context:component-scan base-package="main">


    <context:exclude-filter type="annotation"
    expression="org.springframework.context.annotation.Configuration" />


    </context:component-scan>


 </beans>
 

最后是crud的测试类

package main.test;


import main.dao.Repository;
import main.impl.RepositoryImpl;
import main.pojo.Tree;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MongoTest {
    public static void main(String[] args) {
        System.out.println("进来了");
        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:/main/applicationContext.xml");
        Repository repository = context.getBean(RepositoryImpl.class);
        // cleanup collection before insertion
        repository.dropCollection();
        // create collection
        repository.createCollection();
        //增长
        repository.saveObject(new Tree("1", "Apple Tree", 10));
        System.out.println("1. " + repository.getAllObjects());


        //增长和查询
        repository.saveObject(new Tree("2", "Orange Tree", 3));
        System.out.println("2. " + repository.getAllObjects());
        System.out.println("Tree with id 1" + repository.getObject("1"));


        //修改
        repository.updateObject("1", "Peach Tree");
        System.out.println("3. " + repository.getAllObjects());


        //删除
        repository.deleteObject("2");
        System.out.println("4. " + repository.getAllObjects());
    }


}

到此,简单的spring-data集成 mongoDB的curd就完成了

后续有不少开发填坑的文章发布,若是对你有帮助,请支持和加关注一下

http://e22a.com/h.05ApkG?cv=AAKHZXVo&sm=339944

https://shop119727980.taobao.com/?spm=0.0.0.0 

相关文章
相关标签/搜索