MaBatis操作更新或读取BLOB字段方法

工作原因,需要对数据库中的Excel模板操作,字段为BLOB字段,以前没操作过,百度了一大堆,方法也是各不相同,现在写出来了,分享出来,供大家参考

这个是读取数据库里的BLOB字段保存的Excel模板

****************************************************************************************************

首先Controller

@Autowired

private SummaryCountService countService;

@RequestMapping(method = RequestMethod.GET value = "/viewTemplate")

public void ViewTemplate(HttpServletResponse response){

    response.reset();

    response.setCharacterEncoding("utf-8");

    response.setHeader("Content-Disposition","attachement; filename = template.xlsx");

    response.setContentType("application/ms-excel");

    countService.viewTemplate(response);

}

接着Service就是一个抽象方法,没什么好说的,直接说ServiceImpl,异常直接抛出,这样便于理解逻辑

public void viewTemplate(HttpServletResponse response) throws SQLException,IOException{

    BLOB blob = (BLOB)****Dao.queryTemplate().getTargetFile();//实体存的Object类型

    InputStream is = blob.getBinaryStream();

    OutputStream os = response.getOutputStream();

    byte[] bytes = new byte[1024];

    for( int i ;(i = is.read(bytes)) > 0 ; ){  os.write(bytes, 0, i);  } //便于理解,写到一行了

    if( os != null ){ is.close();  os.close()  }

}

然后Dao层就是一个抽象方法

再说mapper映射

   

    

这样就把数据库中的BLOB文件读出来,并返到前端了

*********************************************************************************************************

再说更新数据库的BLOB字段

同上,首先Controller

@RequestMapping(method = RequestMethod.GET, value = "/updateTemplate")

public Object updateTemplate(@RequestParam MutipartFile file){

    return  countService.updateTemplate(file);

}

Service 略过,直接说serviceImpl,异常我就直接抛出了,便于理解

public Object updateTemplate(MutipartFile file) throws IOException{

    JSONObject result = new JSONObject();

    InputStream is = file.getInputStream();

    byte[] bytes = FileCopyUtils.copyToByteArray(is);

    int i = ****Dao.updateBlob(byte);

    if(i != 0 ){ 

        result.put("Status","true")

     }else{ 

        resultput("Status","false");

 }

return result;

}

dao层直接略过,说Mapper映射文件

    update 表名 set targetFile = #{blobFile} where 过滤条件


你可能感兴趣的:(MaBatis操作更新或读取BLOB字段方法)