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());
}
}
}
}
相關文章
- SpringData JDBCSpringJDBC
- mongoDB操作MongoDB
- Es-SpringDataSpring
- PHP 操作 MongoDBPHPMongoDB
- Mongodb 管理操作MongoDB
- MongoDB基本操作MongoDB
- JavaApi操作MongoDBJavaAPIMongoDB
- Go操作MongoDBMongoDB
- Scala操作MongoDBMongoDB
- Java操作MongoDBJavaMongoDB
- MongoDB相關操作MongoDB
- MongoDB之基本操作MongoDB
- 使用mongoskin操作MongoDBMongoDB
- Mongodb 常用操作命令MongoDB
- MongoDB更新(update)操作MongoDB
- 【mongoDB】常用操作命令MongoDB
- MongoDB基礎操作MongoDB
- nodejs操作mongodb資料庫(mongodb)NodeJSMongoDB資料庫
- SpringData 完全入門指南Spring
- MongoDB(7)- 文件插入操作MongoDB
- MongoDB 資料庫操作MongoDB資料庫
- Mongodb-基礎操作MongoDB
- mongodb資料庫操作MongoDB資料庫
- mongodb聚合操作記錄MongoDB
- MongoDB 基本操作詳解MongoDB
- MongoDB系列一(索引及C#如何操作MongoDB)MongoDB索引C#
- Springboot與springdata JPASpring Boot
- 框架系列——SpringData 、JPA 、SpringDataJPA框架Spring
- MongoDB的常用Query操作及操作符MongoDB
- mongodb批量操作, bulk_write,MongoDB
- C#簡單操作MongoDBC#MongoDB
- MongoDB增刪改查操作MongoDB
- MongoDB學習之聚合操作MongoDB
- MongoDB分片叢集常用操作MongoDB
- MongoDB之資料增加操作MongoDB
- mongodb 的事務性操作MongoDB
- MongoDB 入門教程系列之三:使用 Restful API 操作 MongoDBMongoDBRESTAPI
- 【MongoDB學習筆記】-使用 MongoDB 進行 CRUD 操作(上)MongoDB筆記