springmvc+mongodb+maven 項目測試代碼

來源:互聯網
上載者:User

標籤:java   springmvc   mongodb   測試   

配置請看我另一篇文章,後續還會有,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;@Documentpublic 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自訂 */@Testpublic 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);}@Testpublic 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("擷取全部的資料----------------------");}@Testpublic void testFindById() {User user = this.mongoDBBaseDao.findById(User.class, "1234567");System.out.println(user.getUsername());System.out.println("擷取單個對象----------------------");}@Testpublic 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);}@Testpublic 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);}@Testpublic 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);}}


springmvc+mongodb+maven 項目測試代碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.