

MongoDB:mongodb在项目开发时的安全验证、分页查询操作。 对于数据库而言,在项目应用中都需要安全验证,不然,就会报错,呵呵~~ 现在贴出来我在项目中是怎么做的。 数据源bean: package com.ishowchina.user.dao;import com.mongodb.BasicDBObject;impo
MongoDB:mongodb在项目开发时的安全验证、分页查询操作。
对于数据库而言,在项目应用中都需要安全验证,不然,就会报错,呵呵~~
现在贴出来我在项目中是怎么做的。
数据源bean:
package com.ishowchina.user.dao;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
public class DataSource {
private String ip;//数据库连接信息要从配置文件中获取 参考appconfig.properties文件
private Integer port;
protected String dbName;
protected Boolean auth;
protected String userName;
protected String passWord;
//打开连接 此处在获取数据库信息(ip、账户、密码等)后,打开数据库。
public MongoClient OpenConnection() throws Exception{
MongoClient mongoClient = new MongoClient( ip,port);
return mongoClient;
}
//获取数据集 此处为数据库安全验证
public DBCollection getCollection(MongoClient client,String tableName){
if(client==null){
return null;
}else {
DB db = client.getDB(getDbName());//获取数据库
boolean r=true;//验证用户及密码
if(auth!=null && auth.equals(true)){
r = db.authenticate(userName, passWord.toCharArray());//密码验证
}
if(r){
DBCollection coll = db.getCollection(tableName);//获取数据集
return coll;
}else {
return null;
}
}
}
//释放连接
public void ReleaseConnection(MongoClient mongoClient){
if(mongoClient!=null){
mongoClient.close();
}
}
//删除操作,注意要传入参数
public void deleteObject(DBObject o,DBCollection col){
col.remove(o);
}
//分页查询 分页查询mongodb已经为我们集成了,只需调用api就行
public DBCursor queryPage(DBObject query,DBObject sort,int start,int limit,DBCollection col){
//.sort('account',1).limit(10),int count = cursor.count()
BasicDBObject exp=new BasicDBObject("_id",0);
return col.find(query,exp).sort(sort).skip(start).limit(limit);
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getDbName() {
return dbName;
}
public Boolean getAuth() {
return auth;
}
public void setAuth(Boolean auth) {
this.auth = auth;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
appconfig.properties配置文件的内容,配置数据库源信息
mongo.ip=160.0.0.243 mongo.port=27017 mongo.auth=true mongo.user=ucenter mongo.pwd=user2show mongo.dbName=ucenter
spring-servlet.xml
classpath:appconfig.properties
