一、Springboot整合MongoDB
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、添加配置
spring:
data:
mongodb:
host: ${host}
port: ${port}
username: ${username}
password: ${password}
database: ${databse}
authenticationDatabase: ${auth_database}
3、添加配置类
@Configuration
public class MongoDBConfig {
@Bean
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
MongoMappingContext context, BeanFactory beanFactory) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
return mappingConverter;
}
}
3、创建操作实体
@Data
@Document(collection="tb_mg_book")
public class Book implements Serializable {
@Id
private String id;
private Integer price;
private String name;
private String info;
private String publish;
private Date createTime;
private Date updateTime;
}
5、mongoDB基础方法封装
public abstract class MongoDbDao<T> {
protected abstract Class<T> getEntityClass();
@Autowired
private MongoTemplate mongoTemplate;
public T queryById(Integer id) {
Query query = new Query(Criteria.where("_id").is(id));
return this.mongoTemplate.findOne(query, this.getEntityClass());
}
public List<T> queryList(T object) {
Query query = getQueryByObject(object);
return mongoTemplate.find(query, this.getEntityClass());
}
public T queryOne(T object) {
Query query = getQueryByObject(object);
return mongoTemplate.findOne(query, this.getEntityClass());
}
public List<T> getPage(T object, int start, int size) {
Query query = getQueryByObject(object);
query.skip(start);
query.limit(size);
logger.info("-------------->MongoDB queryPage start");
return this.mongoTemplate.find(query, this.getEntityClass());
}
public Long getCount(T object) {
Query query = getQueryByObject(object);
logger.info("-------------->MongoDB Count start");
return this.mongoTemplate.count(query, this.getEntityClass());
}
public void save(T t) {
this.mongoTemplate.save(t);
}
public int delete(T t) {
logger.info("-------------->MongoDB delete start");
return (int) this.mongoTemplate.remove(t).getDeletedCount();
}
public void deleteById(Integer id) {
Criteria criteria = Criteria.where("_id").is(id);
if (null != criteria) {
Query query = new Query(criteria);
T obj = this.mongoTemplate.findOne(query, this.getEntityClass());
logger.info("-------------->MongoDB deleteById start");
if (obj != null) {
this.delete(obj);
}
}
}
public void updateFirst(T srcObj, T targetObj){
Query query = getQueryByObject(srcObj);
Update update = getUpdateByObject(targetObj);
logger.info("-------------->MongoDB updateFirst start");
this.mongoTemplate.updateFirst(query,update,this.getEntityClass());
}
public void updateMulti(T srcObj, T targetObj){
Query query = getQueryByObject(srcObj);
Update update = getUpdateByObject(targetObj);
logger.info("-------------->MongoDB updateFirst start");
this.mongoTemplate.updateMulti(query,update,this.getEntityClass());
}
public void updateInsert(T srcObj, T targetObj){
Query query = getQueryByObject(srcObj);
Update update = getUpdateByObject(targetObj);
logger.info("-------------->MongoDB updateInsert start");
this.mongoTemplate.upsert(query,update,this.getEntityClass());
}
private Query getQueryByObject(T object) {
Query query = new Query();
String[] fileds = getFiledName(object);
Criteria criteria = new Criteria();
for (int i = 0; i < fileds.length; i++) {
String filedName = (String) fileds[i];
Object filedValue = getFieldValueByName(filedName, object);
if (filedValue != null) {
criteria.and(filedName).is(filedValue);
}
}
query.addCriteria(criteria);
return query;
}
private Update getUpdateByObject(T object) {
Update update = new Update();
String[] fileds = getFiledName(object);
for (int i = 0; i < fileds.length; i++) {
String filedName = (String) fileds[i];
Object filedValue =getFieldValueByName(filedName, object);
if (filedValue != null) {
update.set(filedName, filedValue);
}
}
return update;
}
private static String[] getFiledName(Object o) {
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; ++i) {
fieldNames[i] = fields[i].getName();
}
return fieldNames;
}
private static Object getFieldValueByName(String fieldName, Object o) {
try {
String e = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + e + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[0]);
return method.invoke(o, new Object[0]);
} catch (Exception var6) {
return null;
}
}
}
- 参照:http://www.ityouknow.com/springboot/2017/05/08/spring-boot-mongodb.html
- https://blog.csdn.net/qq_22136439/article/details/113557020?spm=1001.2014.3001.5501
- 结合目前的企业实践