Java端要向mongoDB插入java对象时,这里用了morphia开源组件。官网:code.google.com/p/morphia
jar包下载:http://download.csdn.net/detail/shiyuezhong/4553453
基于maven开发
db.properties配置文件:
#主机地址 端口(默认) 数据库名
db.host=localhost
db.port=27017
app.db.name=test
Spring配置文件: applicationContext.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: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代码: BaseDao.java
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);
}*/
public void save(Class clazz){
dt.save(clazz);
}
@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类: Page.java
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): BaseEntity.java:
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类:Test2.java:
package com.syz.test;
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 Test2 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BaseDao baseDao = (BaseDao) context.getBean("baseDao");
System.out.println("----------------------");
/*//添加
BaseEntity be0 = new BaseEntity();
be0.setTitle("ssq");
be0.setPlace("成都");
be0.setCreateTime(new Date());
try{
baseDao.save(be0);
System.out.println("成功!!!!!!!!!!!!");
}catch (Exception e) {
e.printStackTrace();
System.out.println("失败-------------");
} */
/* //模糊查询和非模糊查询
//System.out.println("*****************");
// List<BaseEntity> list0 = baseDao.findByNameFuzzyQuery(BaseEntity.class, "title","s");
List<BaseEntity> list0 = baseDao.findByName(BaseEntity.class,"title", "ssq");//非模糊
System.out.println(list0.size());
for(BaseEntity be : list0){
System.out.println(be.getTitle()+" "+be.getPlace());
}*/
/* //根据ID查询
List<BaseEntity> list1 = baseDao.findById(BaseEntity.class, ObjectId.massageToObjectId("50179368763b18ca87e9ad3a"));
for(BaseEntity be : list1){
System.out.println(be.getId()+" "+be.getTitle()+" "+be.getPlace());
} */
//根据自定义进行修改
try{
List<BaseEntity> l = baseDao.findByName(BaseEntity.class, "title", "ssq");
if(l.size() == 0){
System.out.println("名称不存在..........");
}else{
for(BaseEntity be : l){
be.setTitle("ass");
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());
}
System.out.println("********************");
//查询全部
List<BaseEntity> list2 = baseDao.findAll(BaseEntity.class);
for(BaseEntity be1 : list2){
System.out.println(be1.getTitle()+" "+be1.getPlace()+" "+be1.getCreateTime()+" "+be1.getId());
}
}
}
==========================================================
以下为另处收集:
Mongo是没有like查询的方式的
要进行模糊匹配只能借助于正则表达式
· Mongo m=new Mongo();
· DB db=m.getDB("UserDB");
· DBCollection collection=db.getCollection("userCollection");
· BasicDBObject cond=new BasicDBObject();
·
·
· if(province!=""){
· cond.put("province", province);
· }
· if(area!=""){
· cond.put("area", area);
· }
· if(keywords!=""){
· Pattern pattern=Pattern.compile("^.*"+keywords+".*$");
· cond.put("name", pattern);
· }
·
·
· DBCursor returns=collection.find(cond);
还有一种是mongoDB 和Spring结合的 Spring-data的模式查询 代码如下 :
·
· public List<User> findUserTop9(String s) {
·
· mongoTemplate.setDatabaseName("UserDB");
· mongoTemplate.setDefaultCollectionName("userColl");
·
· List<User> users = mongoTemplate.find(new Query(new Criteria(
· "name").regex(".*?"+"张"+".*")).limit(9), User.class);
·
· return users;
· }