BLOB和CLOB
Posted lukelook
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BLOB和CLOB相关的知识,希望对你有一定的参考价值。
各数据类型及字节长度一览表:
一.BLOB存储(hibernate4)
实体类
package com.my.dm.model; import java.sql.Blob; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="image") public class ImgFile @Id @Column(name="IMG_ID") private String imgId; @Column(name="IMG_NAME") private String imgName; @Column(name="IMG_SIZE") private double imgSize; @Column(name="IMG_CONTENT") private Blob imgContent; /** * @return the imgId */ public String getImgId() return imgId; /** * @param imgId the imgId to set */ public void setImgId(String imgId) this.imgId = imgId; /** * @return the imgName */ public String getImgName() return imgName; /** * @param imgName the imgName to set */ public void setImgName(String imgName) this.imgName = imgName; /** * @return the imgSize */ public double getImgSize() return imgSize; /** * @param imgSize the imgSize to set */ public void setImgSize(double imgSize) this.imgSize = imgSize; /** * @return the imgContent */ public Blob getImgContent() return imgContent; /** * @param imgContent the imgContent to set */ public void setImgContent(Blob imgContent) this.imgContent = imgContent; /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() return "ImgFile [imgId=" + imgId + ", imgName=" + imgName + ", imgSize=" + imgSize + ", imgContent=" + imgContent + "]";
存储测试代码
@Override public void saveImage() // TODO Auto-generated method stub Session session = sessionFactory.getCurrentSession(); ImgFile img = new ImgFile(); img.setImgId(UUID.randomUUID().toString().replace("-", "")); img.setImgName("testImg"); img.setImgSize(1024.00); File file = new File("D:\\test\\pic\\Koala.jpg"); try FileInputStream inputStream = new FileInputStream(file); Blob blob = Hibernate.getLobCreator(session).createBlob(inputStream, file.length());//(inputStream, inputStream.available())
// 也可用 session.getLobHelper().createBlob(inputStream, inputStream.available()); img.setImgContent(blob); session.save(img); catch (FileNotFoundException e) // TODO Auto-generated catch block e.printStackTrace(); catch (IOException e) // TODO Auto-generated catch block e.printStackTrace();
可以用byte[] 创建blob
FileInputStream inputStream = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len = 0 ; while((len = inputStream.read(bytes))!=-1) baos.write(bytes, 0, len); byte[] inByte = baos.toByteArray(); Blob blob = Hibernate.getLobCreator(session).createBlob(inByte);
hibernate3中为:
InputStream in = new FileInputStream("F:\\4563123.jpg"); Blob blob = Hibernate.createBlob(in); //得到简介的clob Clob clob = Hibernate.createClob("这是一本书和详细描述。#(*&#@¥%(*&@¥)(@#¥#¥");
以上是关于BLOB和CLOB的主要内容,如果未能解决你的问题,请参考以下文章
使用 Blob 特定的 SAS 令牌连接和更新 Azure Blob