技术开发 频道

Mongodb数据库入门之Spring Mongodb

   注意这里引用相关的命名空间xmlns:mongo="http://www.springframework.org/schema/data/mongo"
,并且在名为mongoTemplate中注入相关的数据库地址,数据库名即可,使用方法如下:

ApplicationContext ctx = new GenericXmlApplicationContext("mongo-config.xml");

  使用Spring Mongodb实现增删改查操作

  下面通过实例讲解如何使用Spring Mongodb实现增删改查操作,假设我们现在有一个实

  体类user如下:

package com.mkyong.user;
public class User {
private String id;
private String firstname;
private String lastname;
private int age;
//getter and setter methods
}

  接下来,我们看具体的操作代码,如下,这里假设要将user类保存到名为userprofile的数据集中。

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 )
{
ApplicationContext ctx
= new AnnotationConfigApplicationContext(SpringMongoConfig.class);
MongoOperations mongoOperation
= (MongoOperations)ctx.getBean("mongoTemplate");
User user
= new User("1001", "yong", "mook kim", 30);
//保存
mongoOperation.save("userprofile",user);
//查找
User savedUser = mongoOperation.findOne("userprofile",
new Query(Criteria.where("id").is("1001")),
User.
class);
System.out.println(
"savedUser : " + savedUser);
//更新
mongoOperation.updateFirst("userprofile",
new Query(Criteria.where("firstname").is("yong")),
Update.update(
"lastname", "new lastname"));
User updatedUser
= mongoOperation.findOne("userprofile",
new Query(Criteria.where("id").is("1001")),
User.
class);
System.out.println(
"updatedUser : " + updatedUser);
//删除
mongoOperation.remove("userprofile",
new Query(Criteria.where("id").is("1001")),
User.
class);
//显示当前列表
List<User> listUser =
mongoOperation.getCollection(
"userprofile", User.class);
System.out.println(
"Number of user = " + listUser.size());
}
}
0
相关文章