转自:http://limingnihao.iteye.com/blog/1940446
第4章 MongoDB整合Spring
(黎明你好原创作品,转载请注明)
4.1 创建maven项目
4.1.1 repositories
创建maven项目,其中repositories使用spring的maven库:
- <repositories>
- <repository>
- <id>central</id>
- <name>Maven Central</name>
- <url>http://repo1.maven.org/maven2/</url>
- </repository>
- <repository>
- <id>spring-release</id>
- <name>Spring Maven Release Repository</name>
- <url>http://repo.springsource.org/libs-release</url>
- </repository>
- <repository>
- <id>atlassian-m2-repository</id>
- <url>https://m2proxy.atlassian.com/repository/public</url>
- </repository>
- </repositories>
4.1.2 Dependencies
使用到的jar包:
- <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>
4.2 添加spring配置文件
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="liming.mongodb.example" />
- <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="climing.mongodb.example.data.model" />
- <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
- <mongo:repositories base-package="liming.mongodb.example.data.impl" />
- <context:annotation-config />
- </beans>
4.3 增删改查
Userl实现的增删改查:
4.3.1UserEntity
- package liming.mongodb.example.data.model;
- import java.util.Date;
- 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 NameEntity name;
- private int age;
- private int works;
- private Date birth;
- private String password;
- private String regionName;
- private String[] special;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public NameEntity getName() {
- return name;
- }
- public void setName(NameEntity name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getWorks() {
- return works;
- }
- public void setWorks(int works) {
- this.works = works;
- }
- public Date getBirth() {
- return birth;
- }
- public void setBirth(Date birth) {
- this.birth = birth;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getRegionName() {
- return regionName;
- }
- public void setRegionName(String regionName) {
- this.regionName = regionName;
- }
- public String[] getSpecial() {
- return special;
- }
- public void setSpecial(String[] special) {
- this.special = special;
- }
- }
4.3.2 NameEntity
- package liming.mongodb.example.data.model;
- public class NameEntity {
- private String username;
- private String nickname;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getNickname() {
- return nickname;
- }
- public void setNickname(String nickname) {
- this.nickname = nickname;
- }
- }
4.3.3 UserDao
- package liming.mongodb.example.data;
- import java.util.List;
- import liming.mongodb.example.data.model.UserEntity;
- import org.springframework.transaction.annotation.Transactional;
- @Transactional
- public interface UserDao {
- public abstract void _test();
- public abstract void createCollection();
- public abstract List<UserEntity> findList(int skip, int limit);
- public abstract List<UserEntity> findListByAge(int age);
- public abstract UserEntity findOne(String id);
- public abstract UserEntity findOneByUsername(String username);
- public abstract void insert(UserEntity entity);
- public abstract void update(UserEntity entity);
- }
4.3.4 UserDaoImpl
- package liming.mongodb.example.data.impl;
- import java.util.List;
- import java.util.Set;
- import liming.mongodb.example.data.UserDao;
- import liming.mongodb.example.data.model.UserEntity;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.domain.Sort;
- import org.springframework.data.domain.Sort.Direction;
- import org.springframework.data.domain.Sort.Order;
- 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 org.springframework.stereotype.Repository;
- import com.mongodb.DB;
- @Repository
- public class UserDaoImpl implements UserDao {
- public static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
- @Autowired
- private MongoTemplate mongoTemplate;
- @Override
- public void _test() {
- Set<String> colls = this.mongoTemplate.getCollectionNames();
- for (String coll : colls) {
- logger.info("CollectionName=" + coll);
- }
- DB db = this.mongoTemplate.getDb();
- logger.info("db=" + db.toString());
- }
- @Override
- public void createCollection() {
- if (!this.mongoTemplate.collectionExists(UserEntity.class)) {
- this.mongoTemplate.createCollection(UserEntity.class);
- }
- }
- @Override
- public List<UserEntity> findList(int skip, int limit) {
- Query query = new Query();
- query.with(new Sort(new Order(Direction.ASC, "_id")));
- query.skip(skip).limit(limit);
- return this.mongoTemplate.find(query, UserEntity.class);
- }
- @Override
- public List<UserEntity> findListByAge(int age) {
- Query query = new Query();
- query.addCriteria(new Criteria("age").is(age));
- return this.mongoTemplate.find(query, UserEntity.class);
- }
- @Override
- public UserEntity findOne(String id) {
- Query query = new Query();
- query.addCriteria(new Criteria("_id").is(id));
- return this.mongoTemplate.findOne(query, UserEntity.class);
- }
- @Override
- public UserEntity findOneByUsername(String username) {
- Query query = new Query();
- query.addCriteria(new Criteria("name.username").is(username));
- return this.mongoTemplate.findOne(query, UserEntity.class);
- }
- @Override
- public void insert(UserEntity entity) {
- this.mongoTemplate.insert(entity);
- }
- @Override
- public void update(UserEntity entity) {
- Query query = new Query();
- query.addCriteria(new Criteria("_id").is(entity.getId()));
- Update update = new Update();
- update.set("age", entity.getAge());
- update.set("password", entity.getPassword());
- update.set("regionName", entity.getRegionName());
- update.set("special", entity.getSpecial());
- update.set("works", entity.getWorks());
- update.set("name", entity.getName());
- this.mongoTemplate.updateFirst(query, update, UserEntity.class);
- }
- }
4.3.5 测试代码
- package liming.mongodb.example;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.List;
- import liming.mongodb.example.data.UserDao;
- import liming.mongodb.example.data.impl.UserDaoImpl;
- import liming.mongodb.example.data.model.UserEntity;
- import org.springframework.context.ConfigurableApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class ApplicationSpring {
- 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);
- userDao._test();
- UserEntity entity1 = new UserEntity();
- entity1.setId("5");
- entity1.setAge(1);
- entity1.setBirth(new Date());
- entity1.setPassword("asdfasdf");
- entity1.setRegionName("北京");
- entity1.setWorks(1);
- userDao.insert(entity1);
- userDao.update(entity1);
- userDao.createCollection();
- List<UserEntity> list = userDao.findList(0, 10);
- for (UserEntity e : list) {
- System.out.println("all - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
- + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- }
- list = userDao.findListByAge(1);
- for (UserEntity e : list) {
- System.out.println("age=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
- + Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- }
- UserEntity e = userDao.findOne("1");
- System.out.println("id=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
- + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- e = userDao.findOneByUsername("limingnihao");
- System.out.println("username=limingnihao - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
- + Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- System.out.println("DONE!");
- }
- }