If you object has an "Id' property, it will be set with the generated Id from MongoDB.

来源:互联网 发布:adobe软件 mac百度云 编辑:程序博客网 时间:2024/05/29 13:02
If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See Spring's Type Conversion" for more details. 


直接上代码吧:

DaoImpl层有个插入的方法:

@Overridepublic void addBrandTips(BrandTips brandTips) {this.mongoTemplate.insert(brandTips);}

Controller中调用的时候:

@RequestMapping(value="modifyBrandTipsOk",method = RequestMethod.POST)public String modifyBrandTipsOk(HttpServletRequest request,HttpServletResponse response,DefaultMultipartHttpServletRequest multipartRequest,BrandTips brandTips){String id = request.getParameter("id");try{String pic = upLoadFile(multipartRequest, "BrandTips/");if(!StringUtils.isEmpty(pic)){brandTips.setPic(pic);}if(!StringUtils.isEmpty(id)){this.h5BannerService.modifyBrandTips(brandTips);}else{BrandTips newBrandTips = new BrandTips();BeanUtils.copyProperties(brandTips,newBrandTips);newBrandTips.setCt(new Date());this.h5BannerService.addBrandTips(newBrandTips);}}catch(Exception ex){ex.printStackTrace();}return "redirect:listBrandTips";}

这里直接将方法中的对象(brandTips)传递回去,发现数据库多了一条没有id的数据:



ok,那么说明这种方式是错误的,换个思路,用copy属性:BeanUtils.copyProperties(brandTips,newBrandTips);


再次保存发现还是保存不来,我勒个擦!!!!!!


好吧,我只能重新new一个对象,然后再一个一个往里塞值:

@RequestMapping(value="modifyBrandTipsOk",method = RequestMethod.POST)public String modifyBrandTipsOk(HttpServletRequest request,HttpServletResponse response,DefaultMultipartHttpServletRequest multipartRequest,BrandTips brandTips){String id = request.getParameter("id");try{String pic = upLoadFile(multipartRequest, "BrandTips/");if(!StringUtils.isEmpty(id)){if(!StringUtils.isEmpty(pic)){brandTips.setPic(pic);}this.h5BannerService.modifyBrandTips(brandTips);}else{BrandTips newBrandTips = new BrandTips();newBrandTips.setCt(new Date());if(!StringUtils.isEmpty(pic)){newBrandTips.setPic(pic);}if(!StringUtils.isEmpty(brandTips.getTitle())){newBrandTips.setTitle(brandTips.getTitle());}if(!StringUtils.isEmpty(brandTips.getSummary())){newBrandTips.setSummary(brandTips.getSummary());}if(brandTips.getDateType()!=0){newBrandTips.setDateType(brandTips.getDateType());}this.h5BannerService.addBrandTips(newBrandTips);}}catch(Exception ex){ex.printStackTrace();}return "redirect:listBrandTips";}




再回头查看mongo的API,翻译第一段文字得到:

如果你的对象有一个“ID”属性,它将与生成的ID从MongoDB。如果你的ID属性是一个字符串,然后MongoDB ObjectId将用于填充字符串。否则,你的财产从ObjectId型的转换将由弹簧BeanWrapper类,利用API处理类型转换。看到弹簧的类型转换“更多细节。



如果它检测到你有id的属性,它会把id当作一个字符串入库,也就是上面的图1为什么有个空id的数据!

0 0
原创粉丝点击