项目中用到了mongodb这款nosql,虽然spring集成了非常好用的工具类,但新手使用各种操作过程中还是需要查找大量博客,测试大量代码,可能每一个表的操作都会写很多的Criteria等,于是利用spring提供的MongoTemplate类加上泛型和反射和多态等Java特性,完成了一个能够解决掉基本的增删改查操作的类,处理了分表创建和分表索引建立,聚合查询,应该是缩短了不少工时的
@Data
public class MongoCollection {
/** 主键id */
@Id
protected String pkId;
/** 创建时间 */
private Date createTime;
/** 删除标志 */
private int delMark = 1;
@Transient
/** 分页查询条数 */
private int limit;
@Transient
/** 分页查询跳过条数 */
private int skip;
@Transient
/** 按时间查询开始 */
private Date createTimeStart;
@Transient
/** 按时间插叙结束 */
private Date createTimeEnd;
@Transient
/** 排序字段 */
private String orderColumn;
/** 排序方式 */
@Transient
private Direction orderType;
@Transient
/** 排序字段 */
private String groupColumn;
/**
* @Transient 类名 private String cName;
*/
/** 存入集合名 */
public String getCollectionName() {
Document document = this.getClass().getAnnotation(Document.class);
return document.collection();
}
}
@Data
public class QueryResult<T> {
private List<T> list = new ArrayList<T>();
private long count;
}
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@ToString
/**
* 指令记录
*
* @author ling
*/
@Document(collection = "eqp_command_record")
public class EqpCommandRecord extends MongoCollection {
/** imei设备号 */
@Indexed(background = true)
private String imei;
/** 指令缓存ID */
@Indexed(background = true)
private String commandCacheId;
/** 指令內容 */
private String commandText;
/** 操作类型 */
private String act;
/** 指令类型 0代表设备上报,8代表平台下发 */
private int type;
@Override
public String getCollectionName() {
if (StringUtils.isBlank(imei) || null == getCreateTime()) {
throw new RuntimeException("分表字段不足");
}
return new StringBuilder(super.getCollectionName()).append("_").append(GatewayTool.getImeiSplit(imei, 500))
.append(CalendarUtil.formateDate(getCreateTime(), "_yyyy")).toString();
}
}
/**
* 1 查询操作
*
* 1.1 时间区间查询,如对updateTime查询,增加设置updateTimeStart和updateTimeEnd属性
*
* 1.2 单个字段多个状态in查询,如對cmdStatus查詢,增加设置cmdStatusInArray属性
*
* 1.3 单个字段多个状态not in查询,如對cmdStatus查詢,增加设置cmdStatusNinArray属性
*
* 1.4 字段模糊匹配查询,如对imei查询,增加设置imeiRegex属性
*
* 1.5 聚合查询,参数设置入groupColumn参数,也可以带其他过滤条件
* 新增一个聚合结果类,可以对任意字段增加聚合属性,如cmdStatus字段,可以加上cmdStatusSum,cmdStatusAvg,cmdStatusMax,cmdStatusMin属性
* 传入该类的Class对象,即可返回该聚合对象的List集合
*
* 1.6 分页查询,参数设置skip和limit,可以增加其他条件过滤,排序设置orderColumn字段
*
* 2 更新操作
*
* 2.1 数值增加更新,如对way加2 增加设置wayInc属性为2即可
*
* 2.2 数组增加更新,如对cmdStatus更新 增加设置cmdStatusPush数组属性即可
*
* 2.2 数组不重复更新,如对cmdStatus更新 增加设置cmdStatusAddToSet数组属性即可
*
* 2.3 数组删除,如对cmdStatus更新 增加设置cmdStatusPull数组属性即可
*
* 所有属性可以加上spring data的 @Transient注解
*
* @author ling
*/
@Repository
public class CommonMongoRepository {
private @Resource MongoTemplate mongoTemplate;
/**
* 保存,带pkId为更新数据
*
* @param entity
*/
public void save(MongoCollection entity) {
ensureCollection(entity);
mongoTemplate.save(entity, entity.getCollectionName());
}
/**
* 批量保存,带pkId为更新数据
*
* @param split
* 是否分表
*/
public void batchSave(List<MongoCollection> entityList, boolean split) {
if (split) {
for (MongoCollection entity : entityList) {
ensureCollection(entity);
mongoTemplate.insert(entity, entity.getCollectionName());
}
} else {
ensureCollection(entityList.get(0));
mongoTemplate.insert(entityList, entityList.get(0).getCollectionName());
}
}
/**
* 创建集合以及索引创建
*
* @param entity
*/
private void ensureCollection(MongoCollection entity) {
String collectionName = entity.getCollectionName();
if (!mongoTemplate.collectionExists(collectionName)) {
mongoTemplate.createCollection(collectionName);
// 获取生成表的所有索引
Document document = entity.getClass().getAnnotation(Document.class);
List<DBObject> indexList = mongoTemplate.getCollection(document.collection()).getIndexInfo();
// 给分表创建的表添加索引
for (DBObject dbObject : indexList) {
if (!"_id_".equals(dbObject.get("name"))) {
dbObject.removeField("ns");
BasicDBObject bdo = (BasicDBObject) dbObject.get("key");
dbObject.removeField("key");
DBObject indexKeys = new BasicDBObject();
indexKeys.put((String) dbObject.get("name"), bdo.get(dbObject.get("name")));
mongoTemplate.getCollection(collectionName).createIndex(indexKeys, dbObject);
}
}
}
}
/**
* 查询所有 new一个对象传进来即可,只是为了确定泛型类型
*/
@SuppressWarnings("unchecked")
public <T extends MongoCollection> List<T> queryAll(T entity) {
return (List<T>) mongoTemplate.findAll(entity.getClass(), entity.getCollectionName());
}
/**
* 根据条件查询,可分页排序,不支持Date类型查询
*
* @param entity
* @return
*/
@SuppressWarnings("unchecked")
public <T extends MongoCollection> List<T> queryList(T entity) {
Query query = createQuery(entity);
return (List<T>) mongoTemplate.find(query, entity.getClass(), entity.getCollectionName());
}
/**
* 根据条件查询一条数据
*
* @param entity
* @return
*/
@SuppressWarnings("unchecked")
public <T extends MongoCollection> T queryOne(T entity) {
Query query = createQuery(entity);
return (T) mongoTemplate.findOne(query, entity.getClass(), entity.getCollectionName());
}
/**
* 分页列表
*
* @param entity
* @return
*/
@SuppressWarnings("unchecked")
public <T extends MongoCollection> QueryResult<T> queryPagination(T entity) {
QueryResult<T> queryResult = new QueryResult<T>();
Query query = createQuery(entity);
List<T> dataList = (List<T>) mongoTemplate.find(query, entity.getClass(), entity.getCollectionName());
long count = mongoTemplate.count(query, entity.getCollectionName());
queryResult.setList(dataList);
queryResult.setCount(count);
return queryResult;
}
/**
* 统计列表,可分页排序
*
* @param entity
* @return
*/
public <T extends MongoCollection> long countList(T entity) {
Query query = createQuery(entity);
return mongoTemplate.count(query, entity.getClass(), entity.getCollectionName());
}
/**
* 是否存在记录,可分页排序
*
* @param entity
* @return
*/
public <T extends MongoCollection> boolean exists(T entity) {
Query query = createQuery(entity);
return mongoTemplate.exists(query, entity.getClass(), entity.getCollectionName());
}
/**
* 更新
*
* @param conditionEntity
* @param newEntity
*/
public <T extends MongoCollection> void update(T conditionEntity, T newEntity) {
Query query = createQuery(conditionEntity);
Update update = createUpdate(newEntity);
mongoTemplate.updateMulti(query, update, conditionEntity.getClass(), conditionEntity.getCollectionName());
}
/**
* 按条件更新第一条记录
*
* @param conditionEntity
* @param newEntity
*/
public <T extends MongoCollection> void updateById(T newEntity) {
MongoCollection conditionEntity = new MongoCollection();
String id = newEntity.getPkId();
conditionEntity.setPkId(id);// 条件实体需要ID
newEntity.setPkId(null);
Query query = createQuery(conditionEntity);
Update update = createUpdate(newEntity);
mongoTemplate.upsert(query, update, newEntity.getClass(), newEntity.getCollectionName());
}
/**
* 按条件更新第一条记录
*
* @param conditionEntity
* @param newEntity
*/
public <T extends MongoCollection> void updateOne(T conditionEntity, T newEntity) {
Query query = createQuery(conditionEntity);
Update update = createUpdate(newEntity);
mongoTemplate.upsert(query, update, conditionEntity.getClass(), conditionEntity.getCollectionName());
}
/**
* 聚合查询 EqpCommandCache
*
* @param entity
* 查询参数,需要带groupColumn
* @param clazz
* 返回的聚合结果类型
* @return
*/
public <P extends MongoCollection, T> List<T> aggregate(P entity, Class<T> clazz) {
Field[] fields = clazz.getDeclaredFields();
TypedAggregation<P> agg = createTypedAggregation(entity, fields);
// 聚合查询以及返回
AggregationResults<T> result = mongoTemplate.aggregate(agg, entity.getCollectionName(), clazz);
return result.getMappedResults();
}
@SuppressWarnings("unchecked")
private <P extends MongoCollection> TypedAggregation<P> createTypedAggregation(P entity, Field[] fields) {
Criteria criteria = createCriteria(entity);
List<AggregationOperation> operationList = new ArrayList<AggregationOperation>();
// 查询条件
MatchOperation match = Aggregation.match(criteria);
if (StringUtils.isNotBlank(entity.getOrderColumn())) {
// 排序
SortOperation sort = Aggregation.sort(entity.getOrderType(), entity.getOrderColumn());
operationList.add(sort);
}
// 聚合Project
GroupOperation group = Aggregation.group(entity.getGroupColumn());
// 分组字段处理
Set<String> paramProjectList = new HashSet<>();
List<String> resultProjectsList = new ArrayList<>();
paramProjectList.add(entity.getGroupColumn());
resultProjectsList.add(entity.getGroupColumn());
for (Field field : fields) {
String fieldName = field.getName();
String realFieldName = null;
if (fieldName.endsWith("Count")) {
realFieldName = fieldName.substring(0, fieldName.length() - "Count".length());
group = group.count().as(fieldName);
paramProjectList.add(realFieldName);
resultProjectsList.add(fieldName);
} else if (fieldName.endsWith("Sum")) {
realFieldName = fieldName.substring(0, fieldName.length() - "Sum".length());
group = group.sum(realFieldName).as(fieldName);
paramProjectList.add(realFieldName);
resultProjectsList.add(fieldName);
} else if (fieldName.endsWith("Avg")) {
realFieldName = fieldName.substring(0, fieldName.length() - "Avg".length());
group = group.avg(realFieldName).as(fieldName);
paramProjectList.add(realFieldName);
resultProjectsList.add(fieldName);
} else if (fieldName.endsWith("Min")) {
realFieldName = fieldName.substring(0, fieldName.length() - "Min".length());
group = group.min(realFieldName).as(fieldName);
paramProjectList.add(realFieldName);
resultProjectsList.add(fieldName);
} else if (fieldName.endsWith("Max")) {
realFieldName = fieldName.substring(0, fieldName.length() - "Max".length());
group = group.max(realFieldName).as(fieldName);
paramProjectList.add(realFieldName);
resultProjectsList.add(fieldName);
}
}
// 参数Project
String[] paramProjects = new String[paramProjectList.size()];
paramProjectList.toArray(paramProjects);
ProjectionOperation paramProject = Aggregation.project(paramProjects);
// 结果Project
String[] valueProjects = new String[resultProjectsList.size()];
resultProjectsList.toArray(valueProjects);
ProjectionOperation resultProject = Aggregation.project(valueProjects).and(entity.getGroupColumn())
.previousOperation();
operationList.add(match);
operationList.add(paramProject);
operationList.add(group);
operationList.add(resultProject);
TypedAggregation<P> agg = (TypedAggregation<P>) Aggregation.newAggregation(entity.getClass(), operationList);
return agg;
}
/**
* 根据对象属性创建Criteria
*
* @param entity
* @return
*/
private <T extends MongoCollection> Criteria createCriteria(T entity) {
Criteria criteria = new Criteria();
// 组合子类属性以及父类属性
Field[] thisFields = entity.getClass().getDeclaredFields();
Field[] superFields = entity.getClass().getSuperclass().getDeclaredFields();
Field[] fields = new Field[thisFields.length + superFields.length];
System.arraycopy(thisFields, 0, fields, 0, thisFields.length);
System.arraycopy(superFields, 0, fields, thisFields.length, superFields.length);
// 处理条件
List<Criteria> dateCriteriaList = new ArrayList<Criteria>();
try {
for (int i = 0; i < fields.length; i++) {
// 字段名以及字段值
Field field = fields[i];
field.setAccessible(true);
Object fieldValue = field.get(entity);
String fieldName = field.getName();
// 忽略字段
Transient transientFiled = field.getDeclaredAnnotation(Transient.class);
if ((null != transientFiled && !fieldName.endsWith("Regex") && !fieldName.endsWith("Array")
&& !fieldName.endsWith("Start") && !fieldName.endsWith("End")) || fieldName.equals("createTime")
|| null == fieldValue) {
continue;
}
// regex查询
if (field.getType() == String.class && fieldName.endsWith("Regex")) {
for (Field regexFiled : fields) {
if (regexFiled.getName()
.equals(fieldName.substring(0, fieldName.length() - "Regex".length()))) {
// 拼接成List
criteria.and(regexFiled.getName()).regex((String) fieldValue);
break;
}
}
continue;
}
// in查询
if (field.getType().isArray() && fieldName.endsWith("Array")) {
// 反射数组拼接成List
List<Object> valueList = new ArrayList<Object>();
for (int j = 0; j < Array.getLength(fieldValue); j++) {
valueList.add(Array.get(fieldValue, j));
}
for (Field arrayFiled : fields) {
if (arrayFiled.getName()
.equals(fieldName.substring(0, fieldName.length() - "InArray".length()))) {
// 设置in条件
criteria.and(arrayFiled.getName()).in(valueList);
break;
}
if (arrayFiled.getName()
.equals(fieldName.substring(0, fieldName.length() - "NinArray".length()))) {
// 设置nin条件
criteria.and(arrayFiled.getName()).nin(valueList);
break;
}
}
continue;
}
// 开始日期
if (field.getType() == Date.class && fieldName.endsWith("Start")) {
for (Field dateFiled : fields) {
if (dateFiled.getName().equals(fieldName.substring(0, fieldName.length() - "Start".length()))) {
dateCriteriaList.add(Criteria.where(dateFiled.getName()).gte(fieldValue));
break;
}
}
continue;
}
// 结束日期
if (field.getType() == Date.class && fieldName.endsWith("End")) {
for (Field dateFiled : fields) {
if (dateFiled.getName().equals(fieldName.substring(0, fieldName.length() - "End".length()))) {
dateCriteriaList.add(Criteria.where(dateFiled.getName()).lte(fieldValue));
break;
}
}
continue;
}
// 一般字段
if (!String.valueOf(fieldValue).equals("null") && !String.valueOf(fieldValue).equals("0")
&& !String.valueOf(fieldValue).equals("0.0") && !String.valueOf(fieldValue).equals(" ")
&& !String.valueOf(fieldValue).equals("false")) {
criteria.and(fieldName).is(fieldValue);
continue;
}
}
// 日期
if (!dateCriteriaList.isEmpty()) {
Criteria[] dateCriteriaArray = new Criteria[dateCriteriaList.size()];
dateCriteriaList.toArray(dateCriteriaArray);
criteria.andOperator(dateCriteriaArray);
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
return criteria;
}
/**
* 创建Updater
*
* @param newEntity
* @return
*/
private <T> Update createUpdate(T entity) {
Update update = new Update();
Field[] thisFields = entity.getClass().getDeclaredFields();
Field[] superFields = entity.getClass().getSuperclass().getDeclaredFields();
Field[] fields = new Field[thisFields.length + superFields.length];
System.arraycopy(thisFields, 0, fields, 0, thisFields.length);
System.arraycopy(superFields, 0, fields, thisFields.length, superFields.length);
try {
for (Field field : fields) {
field.setAccessible(true);
String fieldName = field.getName();
Object fieldValue = field.get(entity);
Transient transientFiled = field.getDeclaredAnnotation(Transient.class);
if (null != transientFiled) {
continue;
}
if (!fieldName.equals("createTime") && !String.valueOf(fieldValue).equals("null")
&& !String.valueOf(fieldValue).equals("0") && !String.valueOf(fieldValue).equals("0.0")
&& !String.valueOf(fieldValue).equals(" ") && !String.valueOf(fieldValue).equals("false")) {
if (fieldName.endsWith("Inc") && fieldValue instanceof Number) {
// 增加或减少
update.inc(fieldName.substring(0, fieldName.length() - "Inc".length()), (Number) fieldValue);
} else if (fieldName.endsWith("Push")) {
// 加到数组
Object[] valueArray = new Object[Array.getLength(fieldValue)];
for (int j = 0; j < Array.getLength(fieldValue); j++) {
valueArray[j] = Array.get(fieldValue, j);
}
update.pushAll(fieldName.substring(0, fieldName.length() - "Push".length()), valueArray);
} else if (fieldName.endsWith("AddToSet")) {
// 加到非重复数组
Update.AddToSetBuilder asb = update.new AddToSetBuilder(
fieldName.substring(0, fieldName.length() - "AddToSet".length()));
for (int j = 0; j < Array.getLength(fieldValue); j++) {
asb.each(Array.get(fieldValue, j));
}
} else if (fieldName.endsWith("Unset")) {
// 删掉列
update.unset(fieldName.substring(0, fieldName.length() - "Unset".length()));
} else if (fieldName.endsWith("Pull")) {
// 删除指定数组元素
Object[] valueArray = new Object[Array.getLength(fieldValue)];
for (int j = 0; j < Array.getLength(fieldValue); j++) {
valueArray[j] = Array.get(fieldValue, j);
}
update.pullAll(fieldName.substring(0, fieldName.length() - "Pull".length()), valueArray);
} else {
// 一般设置
update.set(fieldName, fieldValue);
}
}
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
return update;
}
/**
* 创建Query
*
* @param entity
* @return
*/
private <T extends MongoCollection> Query createQuery(T entity) {
Criteria criteria = createCriteria(entity);
Query query = new Query(criteria);
if (0 != entity.getLimit()) {
query.limit(entity.getLimit());
}
if (0 != entity.getSkip()) {
query.skip(entity.getSkip());
}
if (!StringUtils.isBlank(entity.getOrderColumn())) {
if (null == entity.getOrderType()) {
entity.setOrderType(Direction.ASC);
}
query.with(new Sort(entity.getOrderType(), entity.getOrderColumn()));
}
return query;
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestCommonMongoRepository {
private @Resource CommonMongoRepository repository;
private @Resource MongoTemplate mongoTemplate;
@Test
public void testSave() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("864811030363888");
eqpLocation.setCreateTime(new Date());
eqpLocation.setAddress("111111");
eqpLocation.setPkId("11111111111111111111");
System.out.println(eqpLocation.getCollectionName());
repository.save(eqpLocation);
}
@Test
public void testBatchSave() {
List<MongoCollection> list = new ArrayList<>();
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("864811030363888");
eqpLocation.setCreateTime(new Date());
eqpLocation.setAddress("111111");
EqpLocation eqpLocation1 = new EqpLocation();
eqpLocation1.setImei("964811030363788");
eqpLocation1.setCreateTime(new Date());
list.add(eqpLocation);
list.add(eqpLocation1);
eqpLocation.setAddress("222222");
repository.batchSave(list, true);
}
@Test
public void testQueryAll() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("864811030363888");
eqpLocation.setCreateTime(new Date());
List<EqpLocation> list = repository.queryAll(eqpLocation);
for (EqpLocation eqpLocation2 : list) {
System.out.println(eqpLocation2);
}
}
@Test
public void testQueryList() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("864811030363888");
eqpLocation.setCreateTime(new Date());
// eqpLocation.setAddress("222222");
// eqpLocation.setLimit(1);
// eqpLocation.setSkip(1);
eqpLocation.setOrderColumn("address");
eqpLocation.setOrderType(Direction.DESC);
List<EqpLocation> list = repository.queryList(eqpLocation);
for (EqpLocation eqpLocation2 : list) {
System.out.println(eqpLocation2);
}
}
@Test
public void testQueryOne() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("14531185518");
eqpLocation.setCreateTime(new Date());
// eqpLocation.setAddress("222222");
// eqpLocation.setLimit(1);
// eqpLocation.setSkip(1);
eqpLocation.setOrderColumn("address");
eqpLocation.setOrderType(Direction.DESC);
EqpLocation list = repository.queryOne(eqpLocation);
System.out.println(list);
}
@Test
public void testQueryById() {
EqpTrack et = new EqpTrack();
et.setPkId("5a783e64168ca00c209cf8fe");
System.out.println(repository.exists(et));
System.out.println(repository.queryOne(et).getPkId());
System.out.println(repository.countList(et));
}
@Test
public void testUpdateById1() {
EqpTrack et = new EqpTrack();
et.setPkId("5a783e64168ca00c209cf8fe");
EqpTrack et2 = new EqpTrack();
et2.setImei("14531185278");// 14531185278
// repository.updateOne(et, et2);
et.setImei("14531185278");
repository.updateById(et);
// System.out.println(repository.exists(et));
// System.out.println(repository.queryOne(et).getPkId());
// System.out.println(repository.countList(et));
}
@Test
public void testQueryPagination() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("864811030363888");
eqpLocation.setCreateTime(new Date());
// eqpLocation.setAddress("222222");
eqpLocation.setLimit(1);
eqpLocation.setSkip(1);
eqpLocation.setOrderColumn("address");
eqpLocation.setOrderType(Direction.DESC);
QueryResult<EqpLocation> queryResult = repository.queryPagination(eqpLocation);
System.out.println(queryResult.getCount());
List<EqpLocation> list = queryResult.getList();
for (EqpLocation eqpLocation2 : list) {
System.out.println(eqpLocation2);
}
}
@Test
public void testCountList() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("14141445989");
eqpLocation.setCreateTime(new Date());
eqpLocation.setLimit(1);
// eqpLocation.setAddress("222222");
long exists = repository.countList(eqpLocation);
System.out.println(exists);
}
@Test
public void testExistsList() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("864811030363888");
eqpLocation.setAddress("1111111");
eqpLocation.setCreateTime(new Date());
boolean b = repository.exists(eqpLocation);
System.out.println(b);
}
@Test
public void testUpdate() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("864811030363888");
eqpLocation.setCreateTime(new Date());
EqpLocation eqpLocation1 = new EqpLocation();
eqpLocation1.setCreateTime(new Date());
eqpLocation1.setCreateTime(new Date());
eqpLocation1.setIsPosition(8);
repository.update(eqpLocation, eqpLocation1);
}
@Test
public void testUpdateEqpStatus() {
// EqpStatus conditionEntity = new EqpStatus();
// conditionEntity.setWorkStatus(CommonConstants.EQP_START);
// conditionEntity.setUpdateTimeEnd(DateUtils.addMilliseconds(new Date(), -1321));
//
// // 更新为离线
// EqpStatus newEntity = new EqpStatus();
// newEntity.setWorkStatus(CommonConstants.EQP_OFFLINE);
// newEntity.setOfflineTime(new Date());
// repository.update(conditionEntity, newEntity);
}
@Test
public void testUpdateOne() {
EqpAlarmIdleSpeed condition = new EqpAlarmIdleSpeed();
condition.setPkId("ccac9ed1-9ee1-43fe-9bff-92ce6e018fcf");
condition.setAddress("123456");
// EqpAlarmIdleSpeed updateContent = new EqpAlarmIdleSpeed();
// updateContent.setAlarmStatus(1);
// repository.updateOne(condition, updateContent);
repository.updateOne(new EqpAlarmIdleSpeed("ccac9ed1-9ee1-43fe-9bff-92ce6e018fcf"), condition);
}
@Test
public void test3() throws ParseException {
EqpLocation el = new EqpLocation();
el.setImei("864811030363888");
el.setDelMark(1);
el.setCreateTime(new Date()); // 创建时间
el.setCreateTimeStart(CalendarUtil.getDateFromPattern("2018-02-02", "yyyy-MM-dd"));
el.setCreateTimeEnd(CalendarUtil.getDateFromPattern("2018-02-03", "yyyy-MM-dd"));
List<EqpLocation> eqpLocation = repository.queryList(el);
for (EqpLocation eqpLocation2 : eqpLocation) {
System.out.println(eqpLocation2);
}
}
@Test
public void testUpdateById() {
EqpLocation el = new EqpLocation();
el.setPkId("5a75211ae7566f1a480c971d");
el.setImei("864811030363888");
el.setDelMark(2);
el.setCreateTime(new Date()); // 创建时间
System.out.println(el.getCollectionName());
repository.updateById(el);
}
@Test
public void testUpdateByIdAddress() {
EqpAddress eqpAddress = new EqpAddress();
eqpAddress.setPkId("6515ce58-d512-4ae0-9fd1-54fd808313cd");
eqpAddress.setCollectionName("eqp_location_68_2008");
eqpAddress.setAddress("dsafdsfsafa456");
repository.updateById(eqpAddress);
}
@Test
public void testQueryWithIn() {
EqpCommandCache cacheParam = new EqpCommandCache();
cacheParam.setCmdStatusInArray(new int[] { 1, 2, 3 });
List<EqpCommandCache> list = repository.queryList(cacheParam);
for (EqpCommandCache eqpCommandCache : list) {
System.out.println(eqpCommandCache);
}
}
@Test
public void testQueryWithNotIn() {
EqpCommandCache cacheParam = new EqpCommandCache();
cacheParam.setCmdStatusNinArray(new int[] { 1, 4 });
List<EqpCommandCache> list = repository.queryList(cacheParam);
for (EqpCommandCache eqpCommandCache : list) {
System.out.println(eqpCommandCache);
}
}
@Test
public void testQueryWithRegex() {
EqpCommandCache cacheParam = new EqpCommandCache();
cacheParam.setValueRegex("8004");
List<EqpCommandCache> list = repository.queryList(cacheParam);
for (EqpCommandCache eqpCommandCache : list) {
System.out.println(eqpCommandCache);
}
}
@Test
public void testUpdateInc() {
EqpTrack el = new EqpTrack();
el.setPkId("49528920-be75-43ea-8bf5-ed7eb1c1d5c4");
el.setImei("14141445989");
el.setSpeedingCountInc(1);
el.setCreateTime(new Date()); // 创建时间
System.out.println(el.getCollectionName());
repository.updateById(el);
}
@Test
public void testUpdatePush() {
EqpCommandCache el = new EqpCommandCache();
el.setPkId("5ff73462-a720-4fda-a81b-901b997e2587");
el.setImei("864811030363888");
el.setTestPush(new String[] { "1", "2", "3" });
System.out.println(el.getCollectionName());
repository.updateById(el);
}
@Test
public void testUpdatePull() {
EqpCommandCache el = new EqpCommandCache();
el.setPkId("5ff73462-a720-4fda-a81b-901b997e2587");
el.setImei("864811030363888");
el.setTestPull(new String[] { "2", "3" });
System.out.println(el.getCollectionName());
repository.updateById(el);
}
@Test
public void testUpdateUnset() {
EqpCommandCache el = new EqpCommandCache();
el.setPkId("5ff73462-a720-4fda-a81b-901b997e2587");
el.setImei("864811030363888");
el.setTypeUnset("Y");
System.out.println(el.getCollectionName());
repository.updateById(el);
}
@Test
public void testAggregate() {
EqpCommandCache cacheParam = new EqpCommandCache();
cacheParam.setGroupColumn("imei");
cacheParam.setImei("14530177127");
List<EqpCommandCacheAggregation> list = repository.aggregate(cacheParam, EqpCommandCacheAggregation.class);
for (EqpCommandCacheAggregation eqpCommandCache : list) {
System.out.print("count:" + eqpCommandCache.getCmdStatusCount());
System.out.print(" sum:" + eqpCommandCache.getCmdStatusSum());
System.out.print(" avg:" + eqpCommandCache.getCmdStatusAvg());
System.out.print(" max:" + eqpCommandCache.getCmdStatusMax());
System.out.println(" min:" + eqpCommandCache.getCmdStatusMin());
}
}
@Test
public void testAggregateNative() {
List<AggregationOperation> operationList = new ArrayList<AggregationOperation>();
ProjectionOperation project = Aggregation.project(new String[] { "imei", "msgNo" });
GroupOperation group = Aggregation.group("imei");
group = group.sum("msgNo").as("cmdStatusSum");
group = group.count().as("cmdStatusCount");
group = group.avg("msgNo").as("cmdStatusAvg");
group = group.max("msgNo").as("cmdStatusMax");
group = group.min("msgNo").as("cmdStatusMin");
ProjectionOperation resultProject = Aggregation.project(new String[] { "imei", "cmdStatusSum", "cmdStatusCount",
"cmdStatusAvg", "cmdStatusMax", "cmdStatusMin" }).and("imei").previousOperation();
resultProject.and("imei").previousOperation();
operationList.add(project);
operationList.add(group);
operationList.add(resultProject);
TypedAggregation<EqpCommandCache> agg = Aggregation.newAggregation(EqpCommandCache.class, operationList);
/*
* Field[] fields = clazz.getDeclaredFields(); TypedAggregation<P> agg =
* createTypedAggregation(entity, fields);
*/
AggregationResults<EqpCommandCacheAggregation> result = mongoTemplate.aggregate(agg, "eqp_command_cache",
EqpCommandCacheAggregation.class);
List<EqpCommandCacheAggregation> list = result.getMappedResults();
for (EqpCommandCacheAggregation eqpCommandCache : list) {
System.out.println(eqpCommandCache);
}
}
@Test
public void testCache() {
EqpCommandCache commandCacheParam = new EqpCommandCache();
commandCacheParam.setImei("14530177127");
commandCacheParam.setCmdStatus(1);
commandCacheParam.setOrderColumn("msgNo");
commandCacheParam.setOrderType(Direction.ASC);
// 查询设备缓存的指令
List<EqpCommandCache> execCommandCacheList = repository.queryList(commandCacheParam);
for (EqpCommandCache eqpCommandCache : execCommandCacheList) {
System.out.println(eqpCommandCache);
}
}
@Test
public void testSplitIndex() {
EqpLocation eqpLocation = new EqpLocation();
eqpLocation.setImei("864811030363888");
eqpLocation.setCreateTime(new Date());
eqpLocation.setAddress("111111");
eqpLocation.setPkId("11111111111111111111");
repository.save(eqpLocation);
}
}