Json数据上传—>对象转换—>存入MongoDB(SpringData提供的规范)

上传json

Json数据上传—>对象转换—>存入MongoDB(SpringData提供的规范)_第1张图片

代码实现

@RestController
@RequestMapping("/api/hosp")
public class ApiController{
	
	@Autowired
	private HospitalService hospitalService;

	@PostMapping("saveHospital")
	public Result saveHosp(HttpServletRequest request){
		Map<String,String[]> parameterMap = request.getParameterMap();
		//调用工具进行类型转换
		Map<String,Object> paramMap = HttpRequestHelper.switchMap(requestMap);

		//调用service方法,添加到数据库
		hospitalService.save(paramMap);
		return Reult.ok();
	}
}
@Service
public class HospitalServiceImpl implements HospitalService{
	
	@Autowired
	private HospitalRepository hospitalRepository;

	@Override
	public void save(Map<String,Object> paramMap){
		
		//通过fastjson工具进行对参数的转换
		String mapString = JSONObject.toJSONString(paramMap);
		Hospital hospital = JSONObject.parseObject(mapString,Hospital.class);
		
		//判断是否存在数据
		String hoscode = hospital.getHoscode();
		Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);
		
		//如果不存在,进行添加,否则修改
		if(hospitalExist != null){
			hospital.setStatus(hospitalExist.getStatus());
			hospital.setCreateTime(hospitalExist.getCreateTime());
			hospital.setUpdateTime(new Date());
			hospital.setIsDeleted(0);
			hospitalRepository.save(hospital);
		}else{
			hospital.setStatus(0);
			hospital.setCreateTime(new Date());
			hospital.setUpdateTime(new Date());
			hospital.setIsDeleted(0);
			hospitalRepository.save(hospital);
		}
		
	}
}

Json数据上传—>对象转换—>存入MongoDB(SpringData提供的规范)_第2张图片
Json数据上传—>对象转换—>存入MongoDB(SpringData提供的规范)_第3张图片

@Repository
public interface HospitalRepository extends MongoRepository<Hospital,String>{
	//判断是否存在数据
	Hospital getHospitalByHoscode(String hoscode);
}

工具

/**
	将map集合的value,由String数组类型转为Object类型
*/
public static Map<String,Object> switchMap(Map<String,String[]> paramMap){
	Map<String,Object> resultMap = new HashMap<>();
	for(Map.Entry<String,String[]> param:paramMap.entrySet()){
		resultMap.put(param.getKey(),param.getValue()[0]);
	}
	return resultMap;
}
/**
	引入依赖fastjson,进行如下转换
	将Map->字符串->对象
*/

数据库MongoDB

通过MongoDB客户端工具查看上传的数据
在这里插入图片描述

Json数据上传—>对象转换—>存入MongoDB(SpringData提供的规范)_第4张图片

你可能感兴趣的:(json,mongodb,java)