Spring Data MongoDB 入门例子

1.以下从官方下载示例,下载地址如下所示:

http://www.springsource.org/samples

 

2.排错,

   刚下载下来的SpringExample有错误,首先它不是一个maven项目,单击右键使其转换成maven项目,添加一些依赖,比如spring-aop,spring-context,spring-core,log4j等依赖。同时更新你的依赖包,依赖配置,最终运行成功后,运行下一步。

 

3.代码讲解。

3.1  方式一(注解方式开启mongo.exe,同时创建数据库yourdb,文档yourCollection),代码如下所示:

package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration;
import com.mongodb.Mongo;

/**
 * Spring MongoDB configuration file
 * 
 */
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration {

	@Override
	public @Bean Mongo mongo() throws Exception {

		return new Mongo("localhost");
	}

	@Override
	public @Bean MongoTemplate mongoTemplate() throws Exception {

		return new MongoTemplate(mongo(),"yourdb","yourCollection");
	}
		
}


3.2方式二(配置文件的方式),代码如下所示:

<?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="localhost" port="27017" />

	<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
		<constructor-arg ref="mongo" />
		<constructor-arg name="databaseName" value="yourdb" />
		<constructor-arg name="defaultCollectionName" value="yourCollection" />
	</bean>

	<!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
	<context:annotation-config />

</beans>


 

3.3 实体类的编写

package com.mkyong.user;

public class User {
		
	private String id;
	private String firstname;
	private String lastname;
	private int age;

	public User(){};
	
	public User(String id, String firstname, String lastname, int age) {
		super();
		this.id = id;
		this.firstname = firstname;
		this.lastname = lastname;
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "User [id=" + id + ", firstname=" + firstname + ", lastname="
				+ lastname + ", age=" + age + "]";
	}
}


 

最后书写main类,如下所示:

package com.mkyong.core;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update;
import com.mkyong.config.SpringMongoConfig;
import com.mkyong.user.User;

public class App
{

    public static void main( String[] args )
    {
    	//For Annotation 注解方式
    	ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    	
    	//For XML XML配置文件方式
    	//ApplicationContext ctx = new GenericXmlApplicationContext("mongo-config.xml");
    	
    	MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
    	
        User user = new User("1001", "yong", "mook kim", 30);
        
        //save
        mongoOperation.save("userprofile",user);
        
        //find
        User savedUser = mongoOperation.findOne("userprofile",
        		new Query(Criteria.where("id").is("1001")),
				User.class);
        
        System.out.println("savedUser : " + savedUser);
        
        //update
        mongoOperation.updateFirst("userprofile",
        		new Query(Criteria.where("firstname").is("yong")), 
        		Update.update("lastname", "new lastname"));
        
        //find
        User updatedUser = mongoOperation.findOne(
        		"userprofile",
        		new Query(Criteria.where("id").is("1001")),
				User.class);
        
        System.out.println("updatedUser : " + updatedUser);
        
        //delete
        mongoOperation.remove("userprofile",
        		new Query(Criteria.where("id").is("1001")),
        		User.class);
        
        //List
        List<User> listUser =  
        	mongoOperation.getCollection("userprofile", User.class);
        System.out.println("Number of user = " + listUser.size());
        
    }
    
}


 由于只是一些CURD的操作,比较简单,直接看代码就明白了,我就不多讲了。

4.运行效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值