mongoDB使用-初学

目前公司项目用了redis做缓存,但是近期想增加一些仅仅插入、查找的简单数据,比如消息、日志这些数据,所以想到了nosql,用了redis进行了尝试,
但是发现redis作为no-sql持久化数据,查询起来很不方便,所以引入了mongoDB进行nosql数据的保存。下面分享下一些初学的使用经验:


一、安装和启动

去mongoDB的官方往网站:http://www.mongodb.org/ 下载,它提供了多个操作系统的版本,这里我用的是linux的。大家也可以在linux直接apt-get,官网都有详细说明。


然后在自己自定义位置建立文件夹,我在mongoDB的跟目录建立了文件夹 data/db


进入mongoDB的目录,sudo ./bin/mongd -dbpath=./data/db启动


二、Java客户端的使用

这里用了spring data mongdb的api

maven添加依赖

<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-mongodb</artifactId>
</dependency>
添加spring配置

<!-- Define the MongoTemplate which handles connectivity with MongoDB -->
  <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongo" ref="mongo"/>
    <constructor-arg name="databaseName" value="test"/>
  </bean>
 
  <!-- Factory bean that creates the Mongo instance -->
  <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
    <property name="host" value="localhost"/>
    <property name="port" value="27017"/>
  </bean>
 
  <!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->
  <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

数据类

public abstract class MongoObject {

	@Id
	protected ObjectId id;//使用objectId和@id保证id唯一

	protected MongoObjectUser creator;

	protected Date createTime = DateUtil.getNowDate();

	/**
	 * id
	 * 
	 * @return
	 */
	public ObjectId getId() {
		return id;
	}

	public void setId(ObjectId id) {
		this.id = id;
	}

	/**
	 * 创建人
	 * 
	 * @return
	 */
	public MongoObjectUser getCreator() {
		return creator;
	}

	public void setCreator(MongoObjectUser creator) {
		this.creator = creator;
	}

	/**
	 * 创建时间
	 * 
	 * @return
	 */
	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public String getIdString() {
		return this.getId().toString();
	}

}
@Document(collection = "notice")
public class Notice extends MongoObject implements Serializable {

	private static final long serialVersionUID = 5734506854619019979L;

	private NoticeType noticeType;

	private String content;

	private String relativeBizId;

	private String lesseeId;

	private String tag;

	/**
	 * 类型
	 */
	public NoticeType getNoticeType() {
		return noticeType;
	}

	public void setNoticeType(NoticeType noticeType) {
		this.noticeType = noticeType;
	}

	/**
	 * 内容
	 */
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	/**
	 * 如果类型是project,relativeBizId则是projectId
	 */
	public String getRelativeBizId() {
		return relativeBizId;
	}

	public void setRelativeBizId(String relativeBizId) {
		this.relativeBizId = relativeBizId;
	}

	/**
	 * 租户ID
	 */
	public String getLesseeId() {
		return lesseeId;
	}

	public void setLesseeId(String lesseeId) {
		this.lesseeId = lesseeId;
	}

	/**
	 * 标签
	 */
	public String getTag() {
		return tag;
	}

	public void setTag(String tag) {
		this.tag = tag;
	}

}

建立repository类

public abstract class MongoDBRepository {

	@Autowired
	private MongoTemplate mongoTemplate;

	protected MongoTemplate getMongoTemplate() throws Exception {
		return this.mongoTemplate;
	}

	public void insert(Object object) throws Exception {
		getMongoTemplate().insert(object);
	}

	public void insertAll(Collection<?> object) throws Exception {
		getMongoTemplate().insertAll(object);
	}

	public void save(Object object) throws Exception {
		getMongoTemplate().save(object);
	}

	public void delete(Object object) throws Exception {
		getMongoTemplate().remove(object);
	}

	public void delete(Criteria criteria, Class<?> entityClass)
			throws Exception {
		Query query = new Query(criteria);
		getMongoTemplate().remove(query, entityClass);
	}

	public void delete(String id, Class<?> entityClass) throws Exception {
		Criteria criteria = Criteria.where("id").is(id);
		delete(criteria, entityClass);
	}

	public void exist(String collectionName) throws Exception {
		getMongoTemplate().collectionExists(collectionName);
	}

	public void exist(Class<?> entityClass) throws Exception {
		getMongoTemplate().collectionExists(entityClass);
	}

	public <T> T findById(String id, Class<T> entityClass) throws Exception {
		ObjectId oid = new ObjectId(id);
		return getMongoTemplate().findById(oid, entityClass);
	}

	protected long getCount(Criteria criteria, Class<?> entityClass)
			throws Exception {
		Query query = new Query(criteria);
		return getMongoTemplate().count(query, entityClass);
	}

	protected void deleteByQuery(Query query, Class<?> entityClass)
			throws Exception {
		getMongoTemplate().remove(query, entityClass);
	}

	protected <T> List<T> pagingByQuery(Criteria criteria,
			Class<T> entityClass, int pageNo) throws Exception {
		return pagingByQuery(criteria, entityClass, pageNo, "createTime",
				Direction.DESC);
	}

	protected <T> List<T> pagingByQuery(Criteria criteria,
			Class<T> entityClass, int pageNo, String orderFeild,
			Direction direction) throws Exception {
		Query query = new Query(criteria);
		query.skip((pageNo - 1) * Constants.MAX_PAGE_ITEMS);
		query.limit(Constants.MAX_PAGE_ITEMS);
		query.with(new Sort(direction, orderFeild));
		return getMongoTemplate().find(query, entityClass);
	}

	protected void updateMulti(Criteria criteria, String key, String value,
			Class<?> entityClass) throws Exception {
		Query query = new Query(criteria);
		getMongoTemplate().updateMulti(query, Update.update(key, value),
				entityClass);
	}

}

业务使用时,继承此类,下面是一个小例子

@Repository
public class NoticeRepository extends MongoDBRepository {

	public List<Notice> getList(int pageNo, String lesseeId,
			String keywords) {
		List<Notice> noticeList = new ArrayList<Notice>();
		String pattern = "^.*" + keywords + ".*$";
		try {
			Criteria criteria = Criteria.where("lesseeId").is(lesseeId);
			if (keywords != null && !keywords.equals("")) {
				criteria.orOperator(new Criteria("tag").regex(pattern),
						new Criteria("content").regex(pattern));
			}
			noticeList = pagingByQuery(criteria, Notice.class, pageNo);
		} catch (Exception e) {
			LoggerUtil.error(NoticeRepository.class, "查询公告失败", e);
		}
		return noticeList;
	}

	public long getTotalCount(String lesseeId) {
		long count = 0;
		try {
			Criteria criteria = Criteria.where("lesseeId").is(lesseeId);
			count = getCount(criteria, Notice.class);
		} catch (Exception e) {
			LoggerUtil.error(NoticeRepository.class, "查询公告总数失败", e);
		}
		return count;
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值