Spring MongoDB集成

8 篇文章 0 订阅
8 篇文章 0 订阅

 

Java端要向mongoDB插入java对象时,我用了到morphia开源组件。官网:code.google.com/p/morphia

只写了DAO层的java代码,能够满足常用的增、删、改、查、分页等操作。

db.properties配置文件:

db.host=localhost //主机地址
db.port=27017 //端口(默认)
app.db.name=app //数据库名

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">

<context:property-placeholder location="classpath:db.properties" />

<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>

DAO代码:

package com.my.dao;

import java.util.List;
import java.util.regex.Pattern;

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());
// }

spring集成mongoDB 是不是很简单啊.

转自:http://charls-007.blog.163.com/blog/static/3545620820113303923636/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值