SpringData操作MongoDB-阿里云开发者社区

开发者社区> 数据库> 正文

SpringData操作MongoDB

简介: 通过SpringData读写MongoDB基础操作
pom.xml添加依赖
<!-- MongoDB -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.4</version>
</dependency>
<!-- spring data -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.4.RELEASE</version>
</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>


mongodb数据库源配置,mongodb-context.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: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.xsd">

<!-- spring连接mongodb数据库的配置 -->
<mongo:mongo-client host="数据库IP" port="数据库端口" credentials="数据库用户名:数据库密码@数据库名称" id="mongo">
<mongo:client-options write-concern="SAFE" />
</mongo:mongo-client>

<mongo:db-factory id="mongoDbFactory" dbname="mongoTest" mongo-ref="mongo" />

<!-- 只要使用这个调用相应的方法操作 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>

<bean id="memberDao" class="mongoDB.MemberDao" />
<bean id="bookDao" class="mongoDB.BookDao" />
</beans>


applicationContext.xml文件引入mongodb配置
<context:component-scan base-package="mongoDB" />
<!-- 导入mongodb的配置文件 -->
<import resource="mongodb-context.xml"/>


测试类-会员
import org.springframework.data.mongodb.core.mapping.DBRef;

public class Member
{
private String id;
private String username;
private String password;
@DBRef
private Book book;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public Book getBook()
{
return book;
}
public void setBook(Book book)
{
this.book = book;
}
}


测试类-书本
import org.springframework.data.mongodb.core.mapping.DBRef;

public class Book
{
private String id;
private String theName;
@DBRef
private Member member;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getTheName()
{
return theName;
}
public void setTheName(String theName)
{
this.theName = theName;
}
public Member getMember()
{
return member;
}
public void setMember(Member member)
{
this.member = member;
}
}


基于DAO,对接MongoTemplate
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.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

public abstract class MongoGenDao<T>
{
@Autowired
protected MongoTemplate mongoTemplate;

/**
 * 保存一个对象
 * 
 * @author http://www.chisalsoft.com
 */
public void save(T t)
{
this.mongoTemplate.save(t);
}

/**
 * 根据Id从Collection中查询对象
 * 
 * @author http://www.chisalsoft.com
 */
public T queryById(String id)
{
Query query = new Query();
Criteria criteria = Criteria.where("_id").is(id);
query.addCriteria(criteria);
return this.mongoTemplate.findOne(query, this.getEntityClass());
}

/**
 * 根据条件查询集合
 * 
 * @author http://www.chisalsoft.com
 */
public List<T> queryList(Query query)
{
return this.mongoTemplate.find(query, this.getEntityClass());
}

/**
 * 通过条件查询单个实体
 * 
 * @author http://www.chisalsoft.com
 */
public T queryOne(Query query)
{
return this.mongoTemplate.findOne(query, this.getEntityClass());
}

/**
 * 通过条件进行分页查询
 * 
 * @author http://www.chisalsoft.com
 */
public List<T> getPage(Query query, int start, int size)
{
query.skip(start);
query.limit(size);
List<T> lists = this.mongoTemplate.find(query, this.getEntityClass());
return lists;
}

/**
 * 根据条件查询库中符合记录的总数,为分页查询服务
 * 
 * @author http://www.chisalsoft.com
 */
public Long getPageCount(Query query)
{
return this.mongoTemplate.count(query, this.getEntityClass());
}

/**
 * 根据Id删除用户
 * 
 * @author http://www.chisalsoft.com
 */
public void deleteById(String id)
{
Criteria criteria = Criteria.where("_id").in(id);
if (null != criteria)
{
Query query = new Query(criteria);
if (null != query && this.queryOne(query) != null)
{
this.mongoTemplate.remove(query);
}
}
}

/**
 * 更新满足条件的第一个记录
 * 
 * @author http://www.chisalsoft.com
 */
public void updateFirst(Query query, Update update)
{
this.mongoTemplate.updateFirst(query, update, this.getEntityClass());
}

/**
 * 更新满足条件的所有记录
 * 
 * @author http://www.chisalsoft.com
 */
public void updateMulti(Query query, Update update)
{
this.mongoTemplate.updateMulti(query, update, this.getEntityClass());
}

/**
 * 查找更新,如果没有找到符合的记录,则将更新的记录插入库中
 * 
 * @author http://www.chisalsoft.com
 */
public void updateInser(Query query, Update update)
{
this.mongoTemplate.upsert(query, update, this.getEntityClass());
}

/**
 * 删除对象
 * 
 * @author http://www.chisalsoft.com
 */
public void delete(T t)
{
this.mongoTemplate.remove(t);
}

/**
 * 为属性自动注入bean服务
 * 
 * @author http://www.chisalsoft.com
 */
public void setMongoTemplate(MongoTemplate mongoTemplate)
{
this.mongoTemplate = mongoTemplate;
}

protected abstract Class<T> getEntityClass();
}


测试类DAO-BOOK
import java.util.List;

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;

@Repository
public class BookDao extends MongoGenDao<Book>
{
/**
 * 分页查询 对应mongodb操作中的 db.book.find().skip(10).limit(10);
 * 
 * @author http://www.chisalsoft.com
 */
public List<Book> queryPage(Book book, Integer start, Integer size)
{
Query query = new Query();
// 此处可以增加分页查询条件Criteria.然后query.addCriteria(criteria);
return this.getPage(query, (start - 1) * size, size);
}

/**
 * 查询满足分页的记录总数
 * 
 * @author http://www.chisalsoft.com
 */
public Long queryPageCount(Book book)
{
Query query = new Query();
// 此处可以增加分页查询条件Criteria.然后query.addCriteria(criteria);
return this.getPageCount(query);
}

/**
 * 更新操作
 * 
 * @author http://www.chisalsoft.com
 */
public void updateFirst(Book book) throws Exception
{
Update update = new Update();
if (null == book.getId() || "".equals(book.getId().trim()))
{
// 如果主键为空,则不进行修改
throw new Exception("Update data Id is Null");
}
if (book.getTheName() != null)
{
update.set("theName", book.getTheName());
}
this.updateFirst(Query.query(Criteria.where("_id").is(book.getId())), update);
}

/**
 * 更新库中所有数据
 * 
 * @author http://www.chisalsoft.com
 */
public void updateMulti(Book book) throws Exception
{
Update update = new Update();
if (null == book.getId() || "".equals(book.getId().trim()))
{
// 如果主键为空,则不进行修改
throw new Exception("Update data Id is Null");
}
if (book.getTheName() != null)
{
update.set("theName", book.getTheName());
}
this.updateMulti(Query.query(Criteria.where("_id").is(book.getId())), update);
}

/**
 * 实现钩子方法,返回反射的类型
 * 
 * @author http://www.chisalsoft.com
 */
@Override
protected Class<Book> getEntityClass()
{
return Book.class;
}
}

测试类DAO-Member
import java.util.List;

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;

@Repository
public class MemberDao extends MongoGenDao<Member>
{
/**
 * 分页查询 对应mongodb操作中的 db.member.find().skip(10).limit(10);
 * 
 * @author http://www.chisalsoft.com
 */
public List<Member> queryPage(Member member, Integer start, Integer size)
{
Query query = new Query();
return this.getPage(query, (start - 1) * size, size);
}

/**
 * 查询满足分页的记录总数
 * 
 * @author http://www.chisalsoft.com
 */
public Long queryPageCount(Member member)
{
Query query = new Query();
return this.getPageCount(query);
}

/**
 * 更新操作
 * 
 * @author http://www.chisalsoft.com
 */
public void updateFirst(Member member) throws Exception
{
Update update = new Update();
if (null == member.getId() || "".equals(member.getId().trim()))
{
// 如果主键为空,则不进行修改
throw new Exception("Update data Id is Null");
}
if (member.getUsername() != null)
{
update.set("username", member.getUsername());
}
if (member.getPassword() != null)
{
update.set("password", member.getPassword());
}
this.updateFirst(Query.query(Criteria.where("_id").is(member.getId())), update);
}

/**
 * 更新库中所有数据
 * 
 * @author http://www.chisalsoft.com
 */
public void updateMulti(Member member) throws Exception
{
Update update = new Update();
if (null == member.getId() || "".equals(member.getId().trim()))
{
// 如果主键为空,则不进行修改
throw new Exception("Update data Id is Null");
}
if (member.getUsername() != null)
{
update.set("username", member.getUsername());
}
if (member.getPassword() != null)
{
update.set("password", member.getPassword());
}
this.updateMulti(Query.query(Criteria.where("_id").is(member.getId())), update);
}

/**
 * 实现钩子方法,返回反射的类型
 * 
 * @author http://www.chisalsoft.com
 */
@Override
protected Class<Member> getEntityClass()
{
return Member.class;
}
}


测试类
import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import api.BaseJunitTest;

@Transactional
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=false)
public class TestMongo extends BaseJunitTest
{
@Autowired
private MemberDao memberDao;

@Autowired
private BookDao bookDao;
@Test
public void execute() throws Exception
{
Member member = new Member();
member.setId("1");
member.setUsername("username1");
member.setPassword("password1");
memberDao.save(member);
}

@Test
public void save2() throws Exception
{
Member member = new Member();
member.setId("2");
member.setUsername("username1");
member.setPassword("password1");
Book book = new Book();
book.setId("1");
book.setTheName("book1");
member.setBook(book);
memberDao.save(member);
}

@Test
public void save3() throws Exception
{
Member member = new Member();
member.setId("3");
member.setUsername("username3");
member.setPassword("password3");
Book book = new Book();
book.setId("3");
book.setTheName("book3");
book.setMember(member);
member.setBook(book);
memberDao.save(member);//在Member和Book互相包含的情况下,若没有设置@DBRef,则此处会规模溢出
bookDao.save(book);
System.out.println("保存完成");
}
@Test
public void update() throws Exception
{
Member member = memberDao.queryById("1");
member.setUsername("username_1");
memberDao.updateFirst(member);
}
@Test
public void getMember() throws Exception
{
Member member = memberDao.queryById("3");
if(member == null)
{
System.out.println("没有这个会员");
}
else
{
System.out.println(member.getUsername());
if(member.getBook() == null)
{
System.out.println("该会员没有book");
}
else
{
System.out.println("该会员有book:"+member.getBook().getTheName());
}
}
}
@Test
public void getBook() throws Exception
{
Book book = bookDao.queryById("3");
if(book != null)
{
System.out.println(book.getTheName());
if(book.getMember() == null)
{
System.out.println("该book没有会员");
}
else
{
System.out.println("该book有会员:"+book.getMember().getUsername());
}
}
else
{
System.out.println("没有找到这本书");
}
}
@Test
public void deleteBook() throws Exception
{
List<Book> bookList = bookDao.queryList(new Query());
for(Book book:bookList)
{
bookDao.delete(book);
}
}
@Test
public void deleteMember() throws Exception
{
List<Member> memberList = memberDao.queryList(new Query());
for(Member member:memberList)
{
memberDao.delete(member);
}
}
@Test
public void queryBook() throws Exception
{
List<Book> bookList = bookDao.queryList(new Query());
if(bookList.size() == 0)
{
System.out.println("没有book");
}
else
{
for(Book book:bookList)
{
System.out.println(book.getTheName());
}
}
}
@Test
public void queryMember() throws Exception
{
List<Member> memberList = memberDao.queryList(new Query());
if(memberList.size() == 0)
{
System.out.println("没有会员");
}
else
{
for(Member member:memberList)
{
System.out.println(member.getUsername());
}
}
}
}

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
数据库
使用钉钉扫一扫加入圈子
+ 订阅

分享数据库前沿,解构实战干货,推动数据库技术变革

其他文章