1、加入lib包,在Maven中
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.5.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.4.2.RELEASE</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.12.1</version> </dependency>
2、在Spring的配置文件中,加入如下的命名空间
xmlns:mongo=http://www.springframework.org/schema/data/mongo 对应的location是:http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd
3、Bean配置
<mongo:mongo host="192.168.174.104" port="20011"></mongo:mongo> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongo"/> <constructor-arg name="databaseName" value="arch1"/> </bean>
4、简单示例
@Repository public class GoodsMongoDao implements GoodsDAO { @Autowired private MongoTemplate mongoTemplate; private final String COLLEC_NAME = "goods"; //增加 public void create(GoodsModel m) { mongoTemplate.insert(m, COLLEC_NAME); } //修改 public void update(GoodsModel m) { DBCollection goods = mongoTemplate.getCollection(COLLEC_NAME); BasicDBObject query = new BasicDBObject("uuid", m.getUuid()); BasicDBObject one = new BasicDBObject().append("uuid", m.getUuid()) .append("name", m.getName()).append("imgPath", m.getImgPath()) .append("description", m.getDescription()); goods.update(query, one); } //删除 public void delete(Integer uuid) { Criteria query = new Criteria("uuid").is(uuid); mongoTemplate.remove(new Query(query), COLLEC_NAME); } //查询 public GoodsModel getByUuid(Integer uuid) { Criteria query = new Criteria("uuid").is(uuid); return mongoTemplate.findOne(new Query(query), GoodsModel.class, COLLEC_NAME); } public List<GoodsQueryModel> getByConditionPage(GoodsQueryModel qm) { return null; } //分页查询 public List<GoodsQueryModel> getByCondition(GoodsQueryModel qm) { Criteria criteria = new Criteria(); if (StringUtils.isNotEmpty(qm.getName())){ criteria.andOperator(new Criteria("name").regex(qm.getName())); } if (StringUtils.isNotEmpty(qm.getName())){ criteria.andOperator(new Criteria("imgPath").regex(qm.getName())); } if (StringUtils.isNotEmpty(qm.getName())){ criteria.andOperator(new Criteria("description").regex(qm.getName())); } Long count=mongoTemplate.count(new Query(criteria), COLLEC_NAME); Page page=qm.getPage(); page.setTotalCount(count.intValue()); List<GoodsQueryModel> results=mongoTemplate.find(new Query(criteria).skip(page.getStart()).limit(page.getPageShow()), GoodsQueryModel.class, COLLEC_NAME); return results; } }