mybatis获取Oracle的Blob字段转成Base64编码

由于借鉴了其他获取Oracle数据库Blob方法,试了多次没有成功,自己磨了两个小时磨了出来,在这里记录下来,以便以后查阅!

这里使用的SpringBoot搭建的maven环境,只需将springboot的包引入即可,并且数据库中需要创建一张测试表,里面有Blob的字段,这里我建的表叫test表,且里面有个blob字段叫ZP

1.创建测试Mapper文件

这里返回的值为Map 类型,即查询的Blob字段放入到Object类型中

@Mapper
public interface TestMapper {
	@Select("select zp from test")
	public List> getList();
}

2.创建测试service接口文件与实现文件

@Repository
public interface TestService {
	public List> getList();
}
@Repository
public class TestServiceImpl implements TestService {
	@Autowired
	TestMapper testMapper;
	public List> getList() {
		return testMapper.getList();
	}
}

3.blob转byte[]、Blob转文件、Blob转base64编码

  /**
	 * 测试方法
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
	   SpringApplication.run(Application.class, args);
	   List>  list = SpringUtils.getBean(TestService.class).getList();
	   for (Map map : list) {
		   BLOB blob = (BLOB)map.get("ZP");  
		   System.out.println(blobToBase64(blob));
		   blobToPic(blob);
	   }
	}
	
	
	/**
	 * blob转base64
	 * @param blob
	 * @throws Exception
	 */
	public static String blobToBase64(Blob blob) throws Exception{
		return Base64.encodeBase64String(blobToByte(blob));
	}
	
	/**
	 * blob转pic
	 * @param blob
	 * @throws Exception
	 */
	public static void blobToPic(Blob blob) throws Exception{
		byte[] bt = blobToByte(blob);
		FileImageOutputStream imageOutput = new FileImageOutputStream(new File("F:/a.png"));
	    imageOutput.write(bt, 0, bt.length);
	    imageOutput.close();
	}
	
	/**
	 * blob转byte
	 * @param blob
	 * @throws Exception
	 */
	public static byte[] blobToByte(Blob blob) throws Exception{
		InputStream is = (InputStream) blob .getBinaryStream();  
	    byte[] bs = new byte[1000];
	    int len = -1;
	    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
	    while((len=is.read(bs)) != -1){
		   os.write(bs, 0, len);
	    }
	    byte[] bt = os.toByteArray();
	    os.close();
	    is.close();
	    return bt;
	}

 

 

 

 

 

 

 

你可能感兴趣的:(java)