配置请看我另一篇文章,后续还会有,mongodb性能测试结果,一个“快”字
要源码包请留下邮箱
代码构造图
直接上代码
BaseDao.java
package com.yiyuwanglu.basecore.dao;
import java.util.List;
public interface BaseDao {
<T> T findById(Class<T> entityClass, String id);
<T> List<T> findAll(Class<T> entityClass);
void remove(Object obj);
void add(Object obj);
void saveOrUpdate(Object obj);
}
MongoDBBaseDao.java
package com.yiyuwanglu.basecore.dao.mongodb;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import com.yiyuwanglu.basecore.dao.BaseDao;
import com.yiyuwanglu.basecore.page.Page;
/**
* mongodb数据泛型dao类
*
* @author hjn
* @version 1.0 2014-09-16
*/
@Repository(value = "mongoDBBaseDao")
public class MongoDBBaseDao implements BaseDao {
@Autowired
@Qualifier("mongoTemplate")
protected MongoTemplate mongoTemplate;
/**
* 根据主键id返回对象
*
* @param id
* 唯一标识
* @return T 对象
*/
public <T> T findById(Class<T> entityClass, String id) {
return this.mongoTemplate.findById(id, entityClass);
}
/**
* 根据类获取全部的对象列表
*
* @param entityClass
* 返回类型
* @return List<T> 返回对象列表
*/
public <T> List<T> findAll(Class<T> entityClass) {
return this.mongoTemplate.findAll(entityClass);
}
/**
* 删除一个对象
*
* @param obj
* 要删除的Mongo对象
*/
public void remove(Object obj) {
this.mongoTemplate.remove(obj);
}
/**
* 添加对象
*
* @param obj
* 要添加的Mongo对象
*/
public void add(Object obj) {
this.mongoTemplate.insert(obj);
}
/**
* 修改对象
*
* @param obj
* 要修改的Mongo对象
*/
public void saveOrUpdate(Object obj) {
this.mongoTemplate.save(obj);
}
/**
* 查询并分页
*
* @param entityClass
* 对象类型
* @param query
* 查询条件
* @param page
* 分页
* @return
*/
public <T> List<T> findByQuery(Class<T> entityClass, Query query, Page page) {
Long count = this.count(entityClass, query);
page.setCount(count);
int pageNumber = page.getCurrent();
int pageSize = page.getPageCount();
query.skip((pageNumber - 1) * pageSize).limit(pageSize);
return this.mongoTemplate.find(query, entityClass);
}
/**
*
* @param entityClass
* 查询对象
* @param query
* 查询条件
* @return
*/
public <T> Long count(Class<T> entityClass, Query query) {
return this.mongoTemplate.count(query, entityClass);
}
/**
* 批量插入
* @param entityClass 对象类
* @param collection 要插入的对象集合
*/
public <T> void addCollection(Class<T> entityClass, Collection<T> collection){
this.mongoTemplate.insert(collection, entityClass);
}
public MongoTemplate getMongoTemplate() {
return mongoTemplate;
}
}
Page.java
package com.yiyuwanglu.basecore.page;
import java.io.IOException;
import java.io.Serializable;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class Page extends SimpleTagSupport implements Serializable {
private static final long serialVersionUID = 1L;//序列号
private Integer current;//当前页码
private Long count;//记录总数
private Integer pageCount;//每页记录数
private String path;//页面链接
private String param;//传入的参数
private boolean notQueryCount = false;//为false在翻页时查询记录总数,默认false
public Page() {
this.current = 1; // 默认第一页
this.count = 0L; // 共多少条记录
this.pageCount = 10; // 默认每页10条记录
}
@Override
public void doTag() throws JspException, IOException {
int pageSize = (int) (this.count / this.pageCount + (this.count % this.pageCount > 0 ? 1 : 0));//共多少页
//显示当前页和总页数
JspWriter out = this.getJspContext().getOut();//指定输入流,用于页面输出分页信息
StringBuffer sb = new StringBuffer();//构建StringBuffer对象,用户拼接分页标签
sb.append("<div class=\"page\">");
sb.append("<ul>");
//如果当前页在第一页,则首页和上一页没有超链接
if (this.current == 1) {
sb.append("<li class=\"disabled\">首页</li><li class=\"disabled\">上一页</li>");
} else {
sb.append("<li><a href=\"");
sb.append(this.path);
sb.append("?current=");
sb.append(1);
if (this.param != null && !"".equals(this.param)) {
sb.append("&");
sb.append(this.param);
}
sb.append("\">首页</a></li>");
sb.append("<li><a href=\"");
sb.append(this.path);
sb.append("?current=");
sb.append(this.current - 1);
if (this.param != null && !"".equals(this.param)) {
sb.append("&");
sb.append(this.param);
}
sb.append("\">上一页</a></li>");
}
//下面的代码显示页码,当前页在中间位置
if (pageSize <= 10) {
for (int i = 1; i <= pageSize; i++) {
//如果页数小于等于10页,则全部显示
if (i == this.current) {//如果页码等于当前页,则该页数没有超链接
sb.append("<li class=\"current\">");
sb.append(i);
sb.append("</li>");
} else {//否则给出超链接
sb.append("<li><a href=\"");
sb.append(this.path);
sb.append("?current=");
sb.append(i);
if (this.param != null && !"".equals(this.param)) {
sb.append("&");
sb.append(this.param);
}
sb.append("\">");
sb.append(i);
sb.append("</a></li>");
}
}
} else {//如果大于10页,则从当前页为中心只显示其中10页
int index = 1;
if (this.current > 4) {//并且如果当前页大于4页,从当前页前4页开始显示10个页数
if (this.current + 4 >= pageSize) {//如果当前页+4 >= 总页数,最后10页全部显示出来
for (int j = pageSize - 9; j <= pageSize; j++) {
if (j == this.current) {//如果页码等于当前页,则该页数没有超链接
sb.append("<li class=\"current\">");
sb.append(j);
sb.append("</li>");
} else {//否则给定超链接
sb.append("<li><a href=\"");
sb.append(this.path);
sb.append("?current=");
sb.append(j);
if (this.param != null && !"".equals(this.param)) {
sb.append("&");
sb.append(this.param);
}
sb.append("\">");
sb.append(j);
sb.append("</a></li>");
}
}
} else {
for (int j = this.current - 4; j <= pageSize; j++) {
if (j == this.current) {//如果页码等于当前页,则该页数没有超链接
sb.append("<li class=\"current\">");
sb.append(j);
sb.append("</li>");
} else {//否则给定超链接
sb.append("<li><a href=\"");
sb.append(this.path);
sb.append("?current=");
sb.append(j);
if (this.param != null && !"".equals(this.param)) {
sb.append("&");
sb.append(this.param);
}
sb.append("\">");
sb.append(j);
sb.append("</a></li>");
}
index++;
if (index > 10) {//如果循环到10次则退出循环
break;
}
}
}
} else {
for (int i = 1; i <= pageSize; i++) {
//如果页数小于等于10页,则全部显示
if (i == this.current) {//如果页码等于当前页,则该页数没有超链接
sb.append("<li class=\"current\">");
sb.append(i);
sb.append("</li>");
} else {//否则给出超链接
sb.append("<li><a href=\"");
sb.append(this.path);
sb.append("?current=");
sb.append(i);
if (this.param != null && !"".equals(this.param)) {
sb.append("&");
sb.append(this.param);
}
sb.append("\">");
sb.append(i);
sb.append("</a></li>");
}
index++;
if (index > 10) {
break;
}
}
}
}
//如果当前页是最后一页,则末页和下一页没有超链接
if (this.current.equals(pageSize) || this.count == 0) {
sb.append("<li class=\"disabled\">下一页</li><li class=\"disabled\">末页</li>");
} else {
sb.append("<li><a href=\"");
sb.append(this.path);
sb.append("?current=");
sb.append(this.current + 1);
if (this.param != null && !"".equals(this.param)) {
sb.append("&");
sb.append(this.param);
}
sb.append("\">下一页</a></li>");
sb.append("<li><a href=\"");
sb.append(this.path);
sb.append("?current=");
sb.append(pageSize);
if (this.param != null && !"".equals(this.param)) {
sb.append("&");
sb.append(this.param);
}
sb.append("\">末页</a></li>");
}
sb.append("</ul>");
sb.append("</div>");
out.print(sb);
}
/**
* 获取总记录条数
*
* @return
*/
public Long getCount() {
return this.count;
}
/**
* 设置总记录条数
*
* @param count
*/
public void setCount(Long count) {
this.count = count;
}
/**
* 获取当前第几页
*
* @return
*/
public Integer getCurrent() {
return this.current;
}
/**
* 设置当前第几页
*
* @param current
*/
public void setCurrent(Integer current) {
try {
if (current <= 0) {
this.current = 1;
} else {
this.current = current;
}
} catch (Exception e) {
this.current = 1;
}
}
/**
* 获取每页多少条记录
*
* @return
*/
public Integer getPageCount() {
return this.pageCount;
}
/**
* 设置每页多少条记录
*
* @param pageCount
*/
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
/**
* 获取URI地址
*
* @return
*/
public String getPath() {
return path;
}
/**
* 设置URI地址
*
* @param path
*/
public void setPath(String path) {
this.path = path;
}
/**
* 获取参数值
*
* @return
*/
public String getParam() {
return param;
}
/**
* 设置参数值
*
* @param param
*/
public void setParam(String param) {
String[] x = param.split("&");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < x.length; i++) {
String[] y = x[i].split("=");
if (y.length > 1 && !"".equals(y[1].trim())) {
sb.append(x[i]);
sb.append("&");
}
}
this.param = sb.toString().substring(0, sb.toString().lastIndexOf("&"));
}
/**
* 获取总页数
*
* @return
*/
public int getPages() {
if (this.count % this.pageCount == 0) {
return (int) (this.count / this.pageCount);
} else {
return (int) (this.count / this.pageCount + 1);
}
}
/**
* 是否为第一页
*
* @return
*/
public boolean firstEnable() {
return previoEnable();
}
/**
* 是否为最后一页
*
* @return
*/
public boolean lastEnable() {
return nextEnable();
}
/**
* 是否有下一页
*
* @return
*/
public boolean nextEnable() {
return this.current * this.pageCount < this.count;
}
/**
* 是否有上一页
*
* @return
*/
public boolean previoEnable() {
return this.current > 1;
}
public boolean isNotQueryCount() {
return this.notQueryCount;
}
public void setNotQueryCount(boolean notQueryCount) {
this.notQueryCount = notQueryCount;
}
/**
* 获取任一页第一条数据在数据集的位置.
*
* @param pageNo 从1开始的页号
* @param pageSize 每页记录条数
* @return 该页第一条数据
*/
public int getStartOfPage(long pageNo, long pageSize) {
return (int) ((pageNo - 1) * pageSize);
}
}
User.java
package com.yiyuwanglu.test.entity;
import java.util.Date;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class User {
private String id;
private String username;
private int age;
private Date createTime;
public User() {
}
public User(String username, int age, Date createTime) {
super();
this.username = username;
this.age = age;
this.createTime = createTime;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
BaseTest.java
package basetest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:config/spring/applicationContext.xml"})
public class BaseTest {
}
TestBaseDao.java
package basetest.dao;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import basetest.BaseTest;
import com.yiyuwanglu.basecore.dao.mongodb.MongoDBBaseDao;
import com.yiyuwanglu.test.entity.User;
public class TestBaseDao extends BaseTest {
@Resource(name = "mongoDBBaseDao")
MongoDBBaseDao mongoDBBaseDao;
/**
* 插入单条数据,id自定义
*/
public void testAdd() {
User user = new User();
Date creatTime = new Date();
user.setCreateTime(creatTime);
user.setAge(10);
user.setUsername("福東江a");
this.mongoDBBaseDao.add(user);
}
/**
* 插入100万条数据,id自定义
*/
@Test
public void testAddCollection() {
List<User> userList = new ArrayList<User>();
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 100000; i++) {
User user = new User();
Date creatTime = new Date();
user.setCreateTime(creatTime);
user.setAge(10);
user.setUsername("冊南");
userList.add(user);
}
}
this.mongoDBBaseDao.add(userList);
}
@Test
public void testFindAll() {
List<User> userList = this.mongoDBBaseDao.findAll(User.class);
for (User user : userList) {
System.out.println("id:" + user.getId() + " username:" + user.getUsername() + " age:" + user.getAge());
}
System.out.println("获取全部的数据----------------------");
}
@Test
public void testFindById() {
User user = this.mongoDBBaseDao.findById(User.class, "1234567");
System.out.println(user.getUsername());
System.out.println("获取单个对象----------------------");
}
@Test
public void testUpdate() {
User user = this.mongoDBBaseDao.findById(User.class, "1234567");
user.setUsername("反倒是淮");
this.mongoDBBaseDao.saveOrUpdate(user);
User newUser = this.mongoDBBaseDao.findById(User.class, "1234567");
System.out.println(newUser.getUsername());
System.out.println("修改数据成功");
this.mongoDBBaseDao.saveOrUpdate(user);
}
@Test
public void testRemove() {
User user = this.mongoDBBaseDao.findById(User.class, "1234567");
this.mongoDBBaseDao.remove(user);
User oldUser = this.mongoDBBaseDao.findById(User.class, "1234567");
if (oldUser == null) {
System.out.println(oldUser == null);
System.out.println("删除对象成功");
}
this.mongoDBBaseDao.add(user);
}
@Test
public void testCount() {
Query query = new Query();
Criteria criteria = new Criteria();
criteria.and("username").is("福東");
query.addCriteria(criteria);
long total = this.mongoDBBaseDao.count(User.class, query);
System.out.println("用户总数:" + total);
}
}