只寫了DAO層的java代碼,可以知足經常使用的增、刪、改、查、分頁等操做。 java
db.properties配置文件: spring
db.host=localhost //主機地址
db.port=27017 //端口(默認)
app.db.name=app //數據庫名 mongodb
Spring配置文件: 數據庫
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> app
<context:property-placeholder location="classpath:db.properties" /> this
<bean id="mongo" class="com.mongodb.Mongo">
<constructor-arg value="${db.host}"></constructor-arg>
<constructor-arg value="${db.port}"></constructor-arg>
</bean>
<bean id="morphia" class="com.google.code.morphia.Morphia"></bean>
<bean id="baseDao" class="com.my.dao.BaseDao">
<constructor-arg ref="mongo"></constructor-arg>
<constructor-arg ref="morphia"></constructor-arg>
<constructor-arg value="${app.db.name}"></constructor-arg>
</bean>
</beans> google
DAO代碼: spa
package com.my.dao; .net
import java.util.List;
import java.util.regex.Pattern; code
import org.bson.types.ObjectId;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
import com.my.entity.BaseEntity;
import com.my.page.Page;
public class BaseDao extends BasicDAO<BaseEntity, ObjectId> {
private Datastore dt;
protected BaseDao(Mongo mongo, Morphia morphia, String dbName) {
super(mongo, morphia, dbName);
dt = morphia.createDatastore(mongo, dbName);
}
public void save(Object entity) {
dt.save(entity);
}
@SuppressWarnings("unchecked")
public List findAll(Class clazz) {
return dt.find(clazz).asList();
}
@SuppressWarnings( { "unchecked" })
public List findByNameFuzzyQuery(Class clazz, String title, Object value) {
Query query = dt.createQuery(clazz);
// Pattern pattern = Pattern.compile("^.*" + key +
// ".*$",Pattern.CASE_INSENSITIVE);
Pattern pattern = Pattern.compile(value.toString(),
Pattern.CASE_INSENSITIVE);
query.filter(title, pattern);
return query.asList();
}
@SuppressWarnings("unchecked")
public List findByName(Class clazz, String title, Object value) {
Query query = dt.createQuery(clazz);
query.filter(title, value);
return query.asList();
}
@SuppressWarnings("unchecked")
public List findById(Class clazz, Object id) {
Query query = dt.createQuery(clazz);
query.filter("_id", id);
return query.asList();
}
@SuppressWarnings("unchecked")
protected Query createNameQuery(Class clazz,String title, Object value) {
return (Query) dt.createQuery(clazz).field(title).equal(value);
}
@SuppressWarnings("unchecked")
protected Query createQuery(Class clazz){
return dt.createQuery(clazz);
}
public void update(Object object) {
dt.save(object);
}
@SuppressWarnings("unchecked")
public void deleteAll(Class clazz) {
Query query = this.createQuery(clazz);
dt.delete(query);
}
@SuppressWarnings("unchecked")
public void deleteByName(Class clazz, String title, Object value) {
Query query = this.createNameQuery(clazz,title, value);
dt.delete(query);
}
@SuppressWarnings("unchecked")
public Query pagingQuery(Class clazz,Page page){
Query q = this.createQuery(clazz);
if(page != null){
q.limit(page.getPageSize()).offset((page.getCurrentPageNo() - 1) * page.getPageSize());
page.setTotal((int)q.countAll());
}
return q;
}
}
分頁用到的Page類:
package com.my.page;
public class Page {
private int currentPageNo; //當前頁數
private int total; //總頁數
private int pageSize; //每頁顯示條數
// 獲得總頁數
public int getTotalPages() {
if (total == 0)
return 1;
return (total + pageSize - 1) / pageSize;
}
// 獲得第一頁頁號
public int getFirstPageNo() {
return 1;
}
// 獲得最後一頁頁號
public int getLastPageNo() {
return getTotalPages();
}
// 獲得上一頁頁號
public int getPrePageNo() {
if (currentPageNo == 1) {
return 1;
}
return currentPageNo - 1;
}
// 獲得下一頁頁號
public int getNextPageNo() {
if (currentPageNo == getTotalPages()) {
return currentPageNo;
}
return currentPageNo + 1;
}
public int getCurrentPageNo() {
return currentPageNo;
}
public void setCurrentPageNo(int currentPageNo) {
this.currentPageNo = currentPageNo;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
實體類(javaBean):
package com.my.entity;
import java.io.Serializable;
import java.util.Date;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
@Entity
//默認是要持久全部對象
public class BaseEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Id
private ObjectId id;
// @Transient 這個表示不持久
private String title; //標題
private String place; //地點
private Date createTime; //建立時間
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
Test類:
import java.util.Date;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.google.code.morphia.query.Query;
import com.my.dao.BaseDao;
import com.my.entity.BaseEntity;
import com.my.page.Page;
public class Test {
public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); BaseDao baseDao = (BaseDao) context.getBean("baseDao"); System.out.println("-------------------"); //添加 // BaseEntity be = new BaseEntity(); // be.setTitle("aha"); // be.setPlace("成都"); // be.setCreateTime(new Date()); // try{ // baseDao.save(be); // System.out.println("成功!!!!!!!!!!!!"); // }catch (Exception e) { // e.printStackTrace(); // System.out.println("失敗-------------"); // } //查詢所有 // List<BaseEntity> list = baseDao.findAll(BaseEntity.class); // for(BaseEntity be : list){ // System.out.println(be.getTitle()+" "+be.getPlace()+" "+be.getCreateTime()+" "+be.getId()); // } // System.out.println("*****************"); //模糊查詢和非模糊查詢 // List<BaseEntity> list = baseDao.findByNameFuzzyQuery(BaseEntity.class, "title","a"); // List<BaseEntity> list = baseDao.findByName(BaseEntity.class,"title", "hao"); // // System.out.println(list.size()); // // for(BaseEntity be : list){ // System.out.println(be.getTitle()+" "+be.getPlace()); // } //根據ID查詢 // List<BaseEntity> list = baseDao.findById(BaseEntity.class, ObjectId.massageToObjectId("4d99992acf8755ee859cbcdb")); // for(BaseEntity be : list){ // System.out.println(be.getId()+" "+be.getTitle()); // } //根據自定義進行修改 // try{ // List<BaseEntity> l = baseDao.findByName(BaseEntity.class, "title", "hehehe"); // if(l.size() == 0){ // System.out.println("名稱不存在.........."); // }else{ // for(BaseEntity be : l){ // be.setTitle("abc"); // be.setPlace("北京"); // baseDao.update(be); // } // // System.out.println("成功!!!!!!!!!!!!!!"); // } // }catch (Exception e) { // System.out.println(e); // } //分頁查詢 // Page p = new Page(); // p.setCurrentPageNo(1); // p.setPageSize(3); // // Query<BaseEntity> l = baseDao.pagingQuery(BaseEntity.class, p); // for(BaseEntity be : l){ // System.out.println(be.getTitle()+" "+be.getPlace()+" "+p.getTotal()); // }