MongoDB整合Spring的操作

来源:互联网 发布:gta5渣电脑神优化20桢 编辑:程序博客网 时间:2024/05/23 14:30

简介

开门见山,记录下这次练习spring与mongodb的整合过程,前段时间学些了mongodb,而现在spring也封装了很多对mongodb的操作

构建项目

我使用的是maven来创建项目
第一步,创建一个Maven项目,配置好pom.xml,我的项目与pom.xml如下
这里写图片描述

配置文件

Dependencies
使用到的jar包如下,使用pom.xml配置
pom.xml

<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>demo.mongodb</groupId>  <artifactId>DemoMongodb</artifactId>  <version>0.0.1-SNAPSHOT</version>  <dependencies>     <dependency>         <groupId>javax.servlet</groupId>         <artifactId>servlet-api</artifactId>         <version>2.5</version>         <type>jar</type>         <scope>provided</scope>     </dependency>     <dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-api</artifactId>         <version>1.6.1</version>         <type>jar</type>         <scope>compile</scope>     </dependency>     <dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-log4j12</artifactId>         <version>1.7.5</version>         <type>jar</type>         <scope>runtime</scope>     </dependency>     <dependency>         <groupId>org.mongodb</groupId>         <artifactId>mongo-java-driver</artifactId>         <version>2.10.1</version>         <type>jar</type>         <scope>compile</scope>     </dependency>     <dependency>         <groupId>org.springframework.data</groupId>         <artifactId>spring-data-mongodb</artifactId>         <version>1.2.1.RELEASE</version>         <type>jar</type>         <scope>compile</scope>     </dependency>     <dependency>         <groupId>org.springframework.data</groupId>         <artifactId>spring-data-mongodb-cross-store</artifactId>         <version>1.2.1.RELEASE</version>         <type>jar</type>         <scope>compile</scope>     </dependency>     <dependency>         <groupId>org.springframework.data</groupId>         <artifactId>spring-data-mongodb-log4j</artifactId>         <version>1.2.1.RELEASE</version>         <type>jar</type>         <scope>compile</scope>     </dependency> </dependencies> </project>

添加spring配置文件

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"     xmlns:mongo="http://www.springframework.org/schema/data/mongo"     xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         http://www.springframework.org/schema/data/mongo               http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd           http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd">     <context:component-scan base-package="mongodb.demo" />     <mongo:mongo host="127.0.0.1" port="27017" />     <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->     <mongo:db-factory dbname="student" mongo-ref="mongo" />     <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />     </bean>     <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->     <mongo:mapping-converter base-package="mongodb.demo.model" />     <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->     <mongo:repositories base-package="mongodb.demo.impl" />     <context:annotation-config /> </beans>

各个类的构建

Model层

首先我们需要一个实体类,这个类对应mongodb中的collection(集合),每个属性对应mongodb的文档,如下,在UserEntity.java中,配置了注解@Document(collection=”user”),表示这个实体对应一个名字叫user的集合,类中的属性有id,name age分别对应文档中的文档名

UserEntity.java

package mongodb.demo.model;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;@Document(collection="user")public class UserEntity {    @Id    private String id;    private String name;    private String 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 getAge() {        return age;    }    public void setAge(String age) {        this.age = age;    }    public String toString() {        String s="id:"+id+"\n name:"+name+"\n age:"+age;        System.out.println(s);        return s;    }}

Dao层

接下来建立操作文档的接口类

UserDao.java

package mongodb.demo.dao;import java.util.List;import org.springframework.transaction.annotation.Transactional;import mongodb.demo.model.UserEntity;@Transactionalpublic interface UserDao {    public void insert(UserEntity userEntity);    public abstract List<UserEntity> findListByAge(String age);}

Dao实现层

然后是上面接口的实现类,这里配置了@Repository,我们用来操作文档

UserDaoImpl.java

package mongodb.demo.dao.impl;import java.util.List;import java.util.Set;import org.springframework.beans.factory.annotation.Autowired;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.stereotype.Repository;import mongodb.demo.dao.UserDao;import mongodb.demo.model.UserEntity;@Repositorypublic class UserDaoImpl implements UserDao{    @Autowired     private MongoTemplate mongoTemplate;     public void insert(UserEntity userEntity) {        // TODO Auto-generated method stub        this.mongoTemplate.insert(userEntity);    }    public List<UserEntity> findListByAge(String age) {        // TODO Auto-generated method stub        Query query = new Query();         query.addCriteria(new Criteria("age").is(age));         return this.mongoTemplate.find(query, UserEntity.class);     }}

最后写个测试类

UserDaoImplTest.java

package mongodb.demo.main;import java.util.ArrayList;import java.util.List;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import mongodb.demo.dao.UserDao;import mongodb.demo.dao.impl.UserDaoImpl;import mongodb.demo.model.UserEntity;public class UserDaoImplTest {    public static void main(String[] args) {        System.out.println("Bootstrapping HelloMongo");         ConfigurableApplicationContext context = null;         context = new ClassPathXmlApplicationContext("applicationContext.xml");         UserDao userDao = context.getBean(UserDaoImpl.class);         UserEntity user=new UserEntity();        user.setId("443");        user.setName("张三");        user.setAge("15");        userDao.insert(user);        List<UserEntity> userList  =new ArrayList<UserEntity>();        userList=userDao.findListByAge("15");        for (UserEntity userEntity : userList) {            userEntity.toString();            System.out.println();        }    }}

看到最后输出如下,构建成功

这里写图片描述

注 : 在我原本的user集合中有数据,所以显示了这么多条要完成以上操作,需要本地Mongodb数据库连接开启,若未开启,请先开启再做测试,开启方式为cmd命令行下,mongod -dbpath=url,url为数据库地址

0 0