话不多说,直接上代码(转载务必说明出处 https://blog.csdn.net/LiaoHongHB/article/details/83900867):
public class MongoDaoImpl<T> implements MongoDao<T> {
/**
* 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(MongoDaoImpl.class);
@Autowired
protected MongoTemplate mongoTemplate;
/**
* clazz
*/
private Class<T> clazz;
public MongoDaoImpl() {
try {
ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
clazz = (Class<T>) type.getActualTypeArguments()[0];
LOGGER.info("reflect Class:{}", clazz);
} catch (Exception e) {
LOGGER.error("MongoDaoImpl reflection happen error:{}", e);
}
}
/**
* 创建对象
*
* @param t
*/
@Override
public void save(T t) throws BbsException {
try {
if (t != null) {
mongoTemplate.save(t);
} else {
throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
}
} catch (Exception e) {
LOGGER.error(String.format("%s save error for MongoDB:", JSON.toJSONString(t)), e);
throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
}
}
/**
* 批量保存
*
* @param entities
*/
@Override
public void saveBatch(List<T> entities) throws BbsException {
try {
if (entities != null && entities.size() > 0) {
mongoTemplate.insert(entities, clazz);
} else {
throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
}
} catch (Exception e) {
LOGGER.error(String.format("%s saveBatch error for MongoDB:{}", JSON.toJSONString(entities)), e);
throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
}
}
/**
* 删除对象
*
* @param id
*/
@Override
public void delete(Serializable id) throws BbsException {
try {
if (id != null) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, clazz);
} else {
throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
}
} catch (Exception e) {
LOGGER.error(String.format("%s delete error for MongoDB:{}", id), e);
throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
}
}
/**
* 更新对象
*
* @param t
*/
@Override
public void update(T t) throws BbsException {
try {
if (t != null) {
Method getId = ReflectionUtils.findMethod(clazz, "getId");
Object id = ReflectionUtils.invokeMethod(getId, t);
Query query = new Query(Criteria.where("id").is(id));
Update update = new Update();
ReflectionUtils.doWithFields(clazz, field -> {
ReflectionUt