官网链接: Jongo.
1.0 依赖
<!--mongodb依赖-->
<dependency>
<groupId>org.jongo</groupId>
<artifactId>jongo</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>de.undercouch</groupId>
<artifactId>bson4jackson</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.2</version>
</dependency>
类似JDBC
封装存和查的工具类
import com.mongodb.DB;
import com.mongodb.MongoClient;
import lombok.extern.slf4j.Slf4j;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Slf4j
@Configuration
public class MongodbMapper<T> {
@Value("${mongodb.host}")
private String host;
@Value("${mongodb.port}")
private int port;
@Value("${mongodb.dbname}")
private String dbname;
@Value("${mongodb.table}")
private String table;
private static DB db;
private static MongoCollection collection;
/*
初始化
*/
@Bean
public MongoCollection init() {
log.info("初始化################");
try {
db = new MongoClient(host, port).getDB(dbname);
Jongo jongo = new Jongo(db);
collection = jongo.getCollection(table);
} catch (UnknownHostException e) {
e.printStackTrace();
}
return collection;
}
/*
查询全部语句
*/
public List<T> queryAll(Class<T> clazz) {
List<T> list = new ArrayList<>();
@SuppressWarnings("unchecked")
Iterator<T> as =(Iterator<T>) collection.find().as(clazz);
while (as.hasNext()) {
T f = as.next();
list.add(f);
}
log.info("========== 查询完成 ===========");
log.info("queryAllResult : " + list);
return list;
}
/*
查询单个语句
*/
public T queryOne(Map<String, String> map, Class<T> clazz) {
String params = "";
String commad = "";
for(String key : map.keySet()) {
params += ("," + key + ":'" + map.get(key) + "'");
}
params.replaceAll(" ","");
if(params.length() > 0) {
if(params.indexOf(",") == 0) {
params = params.substring(1, params.length());
commad = "{" + params + "}";
}
}
log.info("========== 查询完成 ===========");
@SuppressWarnings("unchecked")
T one = (T) collection.findOne(commad).as(clazz);
if(one != null) {
log.info("queryOneResult : " + one.toString());
}
return one;
}
/*
添加语句
*/
public void save(Object object) {
collection.save(object);
log.info("mongodb数据保存成功!");
}
}
直接@Autowaired注入使用