MongoDb的Java客户端配置
一 MongoDb介绍
二 Java客户端配置
三 MongoDB GridFS存取文件
一 MongoDb介绍
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,是类似json的bjson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
二 java客户端配置
2.1 属性配置文件mongo.properties
mongo.databaseName = test_db
mongo.host = 192.168.13.127
mongo.port = 27017
2.2 xml文件springMongoDb.xml
2.3 maven上添加mongodb的包
org.mongodb
mongo-java-driver
3.4.2
org.springframework.data
spring-data-mongodb
1.10.1.RELEASE
2.4 mongodb基础类
MongoIntf.java
package com.mycompany.mongo.dao;
import java.util.List;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
public interface MongoIntf{
/*保存一个对象*/
public void save(T t);
/*根据对象Id查找该对象*/
public T queryById(Class cls,String id);
/*根据条件查询集合*/
public List queryList(Class cls,Query query);
/*通过条件查询单个实体*/
public T queryOne(Class cls,Query query);
/*分页查询*/
public List getPage(Class cls,Query query, int start, int size);
/*查询符合条件的记录总数*/
public Long getPageCount(Class cls,Query query);
/*根据id删除对象*/
public void deleteById(Class cls,String id);
/*删除对象*/
public void delete(T t);
/*更新指定id的属性值*/
public void updateFirst(Class cls,String id, String objName, String objValue);
/*查找更新*/
public void updateInser(Class cls,Query query, Update update);
}
MongoSupport.java
package com.mycompany.mongo.dao;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
public class MongoSupport implements MongoIntf{
private Logger logger = LoggerFactory.getLogger(MongoSupport.class);
@Autowired
public MongoTemplate mongoTemplate;
/**@Description
* 保存一个对象
*/
@Override
public void save(T t){
this.mongoTemplate.save(t);
}
/**@Description
* 查找对应id的对象,id对应Collection中记录的_id字段
*/
public T queryById(Class cls,String id) {
Query query = new Query();
Criteria criteria = Criteria.where("_id").is(id);
query.addCriteria(criteria);
logger.info(cls+"[Mongo]queryById:" + query);
return this.mongoTemplate.findOne(query, cls);
}
/**@Description
* 根据条件查询集合
*/
public List queryList(Class cls,Query query){
logger.info(cls+"[Mongo]queryList:" + query);
return this.mongoTemplate.find(query, cls);
}
/**@Description
* 通过条件查询单个实体
* 查询单个用的是mongoTemplate.findOne方法,查询多条的用的是mongoTemplate.find
*/
public T queryOne(Class cls,Query query){
logger.info(cls+"[Mongo] queryOne:" + query);
return this.mongoTemplate.findOne(query, cls);
}
/**@Description
* 通过条件进行分页查询
* 类似mysql查询中的limit
*/
public List getPage(Class cls,Query query, int start, int size){
query.skip(start);
query.limit(size);
List lists = this.mongoTemplate.find(query, cls);
logger.info(cls+"[Mongo] queryPage:" + query + "(" + start +"," + size +")");
return lists;
}
/**@Description
* 根据条件查询库中符合记录的总数,为分页查询服务
*/
public Long getPageCount(Class cls,Query query){
logger.info(cls+"[Mongo]queryPageCount:" + query);
return this.mongoTemplate.count(query, cls);
}
/**@Description
* 根据id删除对象
*/
public void deleteById(Class cls,String id){
Criteria criteria = Criteria.where("_id").in(id);
if(null!=criteria){
Query query = new Query(criteria);
if(null!=query && this.queryOne(cls,query)!=null){
this.mongoTemplate.remove(this.queryOne(cls,query));
logger.info(cls+"[Mongo]deleteById:" + query);
}
}
}
/**@Description
* 删除对象
*/
public void delete(T t){
this.mongoTemplate.remove(t);
logger.info("[Mongo]delete:" + t);
}
/**@Description
* 更新指定id的属性值
*/
public void updateFirst(Class cls,String id, String objName, String objValue){
Criteria criteria = Criteria.where("_id").in(id);
if(null!=criteria){
Query query = new Query(criteria);
if(null!=query && this.queryOne(cls,query)!=null){
Update update=new Update();
update.set(objName,objValue);
this.mongoTemplate.updateFirst(query,update,cls);
logger.info(cls+"[Mongo]updateFirst:query(" + query + "),update(" + update + ")");
}
}
}
/**
* Created on 2017年3月27日
* Discription:[查找更新,如果没有找到符合的记录,则将更新的记录插入库中]
*/
public void updateInser(Class cls,Query query, Update update){
logger.info(cls+"[Mongo]updateInser:query(" + query + "),update(" + update + ")");
this.mongoTemplate.upsert(query, update, cls);
}
}
2.5 然后在项目的dao层实现方法中,继承mongodb的实现类,如userDao
package com.mycompany.user.dao;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import com.mycompany.mongo.dao.MongoSupport;
import com.mycompany.user.entity.User;
import com.mycompany.user.mapper.UserMapper;
@Repository("userDao")
public class UserDaoImpl extends MongoSupport implements UserDao{
@Autowired
private UserMapper userMapper;
public User selectByUserId(Map map) {
return userMapper.selectByUserId(map);
}
public void insertUser(User user) {
userMapper.insertUser(user);
}
/*保存一个对象*/
@Override
public void saveUser(User user){
this.save(user);
}
/*根据对象Id查找该对象*/
@Override
public User queryUserById(String id){
return this.queryById(User.class, id);
}
/*根据条件查询集合*/
@Override
public List queryUserList(Query query){
return this.queryList(User.class, query);
}
/*通过条件查询单个实体*/
@Override
public User queryOneUser(Query query){
return this.queryOne(User.class,query);
}
/*分页查询*/
@Override
public List getPage(Query query, int start, int size){
return this.getPage(User.class, query, start, size);
}
/*查询符合条件的记录总数*/
@Override
public Long getPageCount(Query query){
return this.getPageCount(User.class, query);
}
/*根据id删除对象*/
@Override
public void deleteById(String id){
this.deleteById(User.class,id);
}
/*删除对象*/
@Override
public void deleteUser(User user){
this.delete(user);
}
/*更新指定id的属性值*/
@Override
public void updateFirst(String id, String objName, String objValue){
this.updateFirst(User.class, id, objName, objValue);
}
/*查找更新*/
@Override
public void updateInser(Query query, Update update){
this.updateInser(User.class, query, update);
}
}
2.6 测试如下
package com.mycompany.mvc.quartz;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import com.mycompany.user.dao.UserDao;
import com.mycompany.user.entity.User;
@Service("jedisClusterTest")
public class JedisClusterTest {
@Autowired
private UserDao userDao;
public void JedisClusterTestMain(){
// jedisClusterClient.set("tStringCluster","helloCluster");
// String tString = jedisClusterClient.get("tStringCluster");
// System.out.println("JedisTest.JedisTestMain():"+tString);
try {
/*新增一个对象*/
// User user = new User();
// user.setUserName("test");
// user.setDescription("password");
// userDao.saveUser(user);
// System.out.println("save:"+user);
/*根据id查找一个对象*/
String id2 = "58e59fd9e4e0310210afac74";
User user2 = userDao.queryUserById(id2);
System.out.println("queryUserById:"+user2);
/*根据条件查询集合*/
List userList3 = new ArrayList();
Query query3 = new Query();
Criteria criteria3 = Criteria.where("userName").is("test");
query3.addCriteria(criteria3);
userList3 = userDao.queryUserList(query3);
System.out.println("queryUserList:"+userList3);
/*单循符合条件的单个*/
Query query4 = new Query();
Criteria criteria4 = Criteria.where("_id").is("58e59fd9e4e0310210afac74");
query4.addCriteria(criteria4);
User user4 = userDao.queryOneUser(query4);
/*查询符合条件的记录数*/
Query query5 = new Query();
Criteria criteria5 = Criteria.where("_id").is("58e59fd9e4e0310210afac74");
query5.addCriteria(criteria5);
Long count = userDao.getPageCount(query5);
System.out.println("getPageCount:"+count);
/*分页查询*/
List userList6 = new ArrayList();
Query query6 = new Query();
Criteria criteria6 = Criteria.where("userName").is("test");
query6.addCriteria(criteria6);
userList6 = userDao.getPage(query6,4,2);
System.out.println("queryUserList:"+userList6);
/*删除*/
// String id7 = "58e59fd9e4e0310210afac74";
// userDao.deleteById(id7);
/*更新指定id的属性值*/
String id8 = "58e5a017e4e0311fa0d501b7";
userDao.updateFirst(id8,"userName","test2");
} catch (Exception e) {
System.out.println(e.getStackTrace());
e.printStackTrace();
}
}
}
三 MongoDB GridFS存取文件
/*使用GridFS来新增一个文件*/
GridFSBucket gridFSBucket = GridFSBuckets.create(testDb);
String file = "src/main/resources/20150315172324.png";
if(!new File(file).exists()){
System.out.println("file is not exists");
}
String filename = "20150315172324.png";
BasicDBObject pic = new BasicDBObject("_id",filename);
GridFSFindIterable gridFSFindIterable = gridFSBucket.find(pic);
if(gridFSFindIterable.first() == null){
Object id = gridFSBucket.uploadFromStream(filename,new FileInputStream(file));
/**files
* 集合有八个属性
*"_id" : ObjectId("4f4608844f9b855c6c35e298"), 唯一id,可以是用户自定义的类型
*"filename" : "CPU.txt", 文件名
*"length" : 778, 文件长度
*"chunkSize" : 262144, chunk的大小
*"uploadDate" : ISODate("2012-02-23T09:36:04.593Z") 上传时间
*"md5" : "e2c789b036cfb3b848ae39a24e795ca6", 文件的md5值
*"contentType" : "text/plain" 文件的MIME类型
*"meta" : null 文件的其它信息,默认是没有”meta”这个key,用户可以自己定义为任意BSON对象
*其中_id、filename、chunkSize、contentType、meta是可以自定义的
*其他如length,uploadDate和md5自己生成的。
*/
/**chunks集合有以下属性
* "_id" : ObjectId("4f4608844f9b855c6c35e299"), chunk的id
* "files_id" : ObjectId("4f4608844f9b855c6c35e298"), 文件的id,对应fs.files中的对象,相当于fs.files集合的外键
* "n" : 0, 文件的第几个chunk块,如果文件大于chunksize的话,会被分割成多个chunk块
* "data" : BinData(0,"QGV...") 文件的二进制数据,这里省略了具体内容
*/
}
/*查找文件*/
BasicDBObject query = new BasicDBObject("filename", filename);
GridFSFile gridFSFile = gridFSBucket.find(query).first();
System.out.println(gridFSFile.getFilename());