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

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

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

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

,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包,如果还缺少什么包,更加报错添加即可

项目需要的目录结构:

每个类中完整的代码贴出如下:

实体类:

这里也解释一下代码注解

<!--解释开始-->

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就完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值