Spring整合Maongdb,本人采用的是Maven进行的构建项目,在此依依说明创建的步骤,分享出来,给各位借鉴。
用Maven项目的同志们肯定知道,Maven是不需要导入jar包的,需要的是坐标,坐标的概念在此就不叙说,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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lgy</groupId>
<artifactId>spring-mongdb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mongdb Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 规范版本 -->
<properties>
<junit-version>4.10</junit-version>
<maven-jetty-plugin-version>6.1.22</maven-jetty-plugin-version>
<spring-version>4.0.0.RELEASE</spring-version>
</properties>
<dependencies>
<!-- spring依赖的jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- mongdb 依赖的jar -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.0</version>
</dependency>
<!-- spring test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- junit test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-mongdb</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>${maven-jetty-plugin-version}</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<useTestClasspath>true</useTestClasspath>
<webAppConfig>
<contextPath>/spring-mongdb</contextPath>
</webAppConfig>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8080</port>
</connector>
</connectors>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
这个配置完之后就需要配置spring的配置文件和Mongdb的配置文件了。
db-config.properties的配置文件:
#mongdb config
mongdb.host = localhost
mongdb.port = 27017
mongdb.database = mydb
beans.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<context:property-placeholder location="classpath:config/db-config.properties"/>
<context:component-scan base-package="com.lgy" />
<context:annotation-config />
<!-- 引入mongdb文件 -->
<import resource="../mongdb/mongdb.xml"/>
</beans>
mongdb.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-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/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Default bean name is 'mongo' -->
<mongo:mongo host="${mongdb.host}" port="${mongdb.port}">
<mongo:options connections-per-host="10"
threads-allowed-to-block-for-connection-multiplier="10"
auto-connect-retry="true" />
</mongo:mongo>
<!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo"/>
<constructor-arg name="databaseName" value="${mongdb.database}"/>
</bean>
</beans>
OK,准备工作差不多,剩下配置代码部分了,在此画下持久层封装的继承体系:
代码如下:
package com.lgy.base;
import java.util.List;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
public interface IBaseDao<T> {
public void save(T t) ;
public T findOneById(Object id);
public List<T> findAll();
public void deleteByModel(T t);
public void deleteByQuery(Query query);
public void update(Query query, Update update);
}
package com.lgy.base;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
public class BaseDaoImpl<T> implements IBaseDao<T> {
@Autowired
protected MongoTemplate mongoTemplate;
protected Class<T> clazz;
@SuppressWarnings("unchecked")
public BaseDaoImpl() {
ParameterizedType pt = (ParameterizedType) this.getClass()
.getGenericSuperclass();
this.clazz = (Class<T>) pt.getActualTypeArguments()[0];
}
public void save(T t) {
this.mongoTemplate.save(t);
}
public T findOneById(Object id) {
return this.mongoTemplate.findById(id, clazz);
}
public List<T> findAll() {
return this.mongoTemplate.findAll(clazz);
}
public void deleteByModel(T t) {
this.mongoTemplate.remove(t);
}
public void deleteByQuery(Query query) {
this.mongoTemplate.remove(query, clazz);
}
public void update(Query query, Update update) {
this.mongoTemplate.upsert(query, update, clazz);
}
}
package com.lgy.dao;
import com.lgy.base.IBaseDao;
import com.lgy.model.Person;
public interface IPersonDao extends IBaseDao<Person> {
}
package com.lgy.dao;
import org.springframework.stereotype.Repository;
import com.lgy.base.BaseDaoImpl;
import com.lgy.model.Person;
@Repository
public class PersonDaoImpl extends BaseDaoImpl<Person> implements IPersonDao {
}
接下来准备测试阶段,model的实体如下:
package com.lgy.model;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="person")
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
public String uid;
public String name;
public int age;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
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;
}
@Override
public String toString() {
return "{USER:{uid:"+this.uid+",name:"+this.name+",age:"+this.age+"}}";
}
}
可能对一些注解不太了解,本人也没有在官方文档上面找到一些说明(英语太差),但是在网上总结了一番常用的注解:
java类转换为mongodb的文档,它有以下几种注释:
1.@Id - 文档的唯一标识,在mongodb中为ObjectId,它是唯一的,通过时间戳+机器标识+进程ID+自增计数器(确保同一秒内产生的Id不会冲突)构成。
2.@Document - 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
3.@Indexed - 声明该字段需要索引,建索引可以大大的提高查询效率。
4.@Transient - 映射忽略的字段,该字段不会保存到MongoDB
5.@CompoundIndex - 复合索引的声明,建复合索引可以有效地提高多字段的查询效率。
6.@PersistenceConstructor - 声明构造函数,作用是把从数据库取出的数据实例化为对象。该构造函数传入的值为从DBObject中取出的数据。
测试如下:
package com.lgy.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.lgy.dao.PersonDaoImpl;
import com.lgy.model.Person;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={"classpath:/config/spring/beans.xml"})
public class MyTest {
@Autowired
private PersonDaoImpl personDao;
@Test
public void insertTest() {
Person p = new Person();
p.setName("66");
p.setAge(11);
personDao.save(p);
System.out.println(p);
}
@Test
public void findOneByIdTest() {
Object id = "11";
Person person = personDao.findOneById(id);
System.out.println(person);
}
@Test
public void deleteByModelTest() {
Object id = "55d5a2f9e81fb76dca877ad4";
Person person = personDao.findOneById(id);
System.out.println(person);
personDao.deleteByModel(person);
}
@Test
public void deleteByQueryTest() {
//所有的条件都是and关系
Criteria criteria = new Criteria();
criteria.and("name").in("dd");
criteria.and("age").in(35);
Query query = new Query();
query.addCriteria(criteria);
personDao.deleteByQuery(query);
}
@Test
public void updateTest() {
//所有的条件都是and关系
Criteria criteria = new Criteria();
criteria.and("name").in("dsd");
Query query = new Query();
query.addCriteria(criteria);
Update update = new Update();
update.set("age", 88);
personDao.update(query, update);
}
@Test
public void findAllTest() {
List<Person> list = personDao.findAll();
for (Person person : list) {
System.out.println(person);
}
}
}
欢迎网友互相探讨!