/** * 使用动态更新的方法更新数据库简单映射字段的内容 * @param entity * @param updateFieldsName * @return */ public T updateSimpleField(T entity , Collection<String> updateFieldsName){ Assert.notEmpty(updateFieldsName , entity.getClass()+"更新字段不能为空。"); Assert.isTrue(!entityInformation.hasCompositeId() , "不支持组合ID更新。"); CriteriaUpdate<T> criteriaUpdate = new CriteriaUpdateImpl<T>( (CriteriaBuilderImpl) entityManager.getCriteriaBuilder()) ; //更新的实体对象 Root<T> root = criteriaUpdate.from(getDomainClass()) ; for (String fieldName : updateFieldsName) { try { //通过反射读取属性的值 PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, entity.getClass()) ; criteriaUpdate.set(fieldName, propertyDescriptor.getReadMethod().invoke(entity,null)) ; } catch (Exception e) { e.printStackTrace(); } } //构造更新过滤条件 String idField = entityInformation.getIdAttributeNames().iterator().next() ; Predicate predicate = entityManager.getCriteriaBuilder().equal( root.get(idField) , entityInformation.getId(entity)) ; criteriaUpdate.where(predicate) ; //执行更新 entityManager.createQuery(criteriaUpdate).executeUpdate() ; return entity ; }
@Before public void setup() { cb = spy(new CriteriaBuilderImpl(null)); }
/** * 查询单个字段 * @param field 字段名称 * @param spec 查询条件 * @return */ public List<String> querySingleFields(String field , Specification<T> spec){ if(StringUtils.isBlank(field)){ return null ; } CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder() ; CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class) ; Root<T> root = applySpecificationToCriteria(spec , query) ; //创建对字段的选择 List<Selection<?>> selectionItems = new ArrayList<>(1) ; selectionItems.add(root.get(field)) ; CompoundSelection<Object[]> compoundSelection = null ; if(criteriaBuilder instanceof CriteriaBuilderImpl){ compoundSelection = ((CriteriaBuilderImpl)criteriaBuilder).array(selectionItems) ; } query.select(compoundSelection) ; TypedQuery<Object[]> typedQuery = entityManager.createQuery(query) ; applySecondLevelCache(typedQuery , spec) ; List<Object[]> list = typedQuery.getResultList() ; //转换查询结果 List<String> resultList = null ; if(list!=null && list.size()>0){ resultList = new ArrayList<>(list.size()) ; //构造查询结果 for (Object object : list) { if(object!=null){ resultList.add(object.toString()) ; } } } return resultList ; }