深入浅出Hibernate之向Mysql插入BLOB,CLOB数据

转自:http://blog.chinaunix.net/uid-1718634-id-2821233.html


mysql version 5.0
 
database name:sample
 
数据表DDL:
 
 create table `sample`.`tuser_blob`(
        `id` int not null auto_increment,
       `name` varchar(50),
       `age` int,
       `versio` int,
       `user_type` int,
       `image` blob,
       `resume` mediumblob,
        primary key (`id`)
    );
TuserBlob.hbm.xml文件:
 
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
" http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
    <class name="org.hibernatetest.bean.TuserBlob" table="tuser_blob">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="50" />
        </property>
        <property name="age" type="java.lang.Integer">
            <column name="age" />
        </property>
        <property name="versio" type="java.lang.Integer">
            <column name="versio" />
        </property>
        <property name="userType" type="java.lang.Integer">
            <column name="user_type" />
        </property>
        <property name="image" type="java.sql.Blob">
            <column name="image" />
        </property>
        <property name="resume" type="java.sql.Clob">
            <column name="resume" />
        </property>
    </class>
</hibernate-mapping>
 
对应的java文件:
package org.hibernatetest.bean;
 
/**
 * TuserBlob generated by MyEclipse - Hibernate Tools
 */
import java.sql.Blob;
import java.sql.Clob;
public class TuserBlob  implements java.io.Serializable {

    // Fields   
     private Integer id;
     private String name;
     private Integer age;
     private Integer versio;
     private Integer userType;
     private Blob image;
     private Clob resume;

    // Constructors
    /** default constructor */
    public TuserBlob() {
    }
    
    /** full constructor */
    public TuserBlob(String name, Integer age, Integer versio, Integer userType, Blob image, Clob resume) {
        this.name = name;
        this.age = age;
        this.versio = versio;
        this.userType = userType;
        this.image = image;
        this.resume = resume;
    }
   
    // Property accessors
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return this.age;
    }
    
    public void setAge(Integer age) {
        this.age = age;
    }
    public Integer getVersio() {
        return this.versio;
    }
    
    public void setVersio(Integer versio) {
        this.versio = versio;
    }
    public Integer getUserType() {
        return this.userType;
    }
    
    public void setUserType(Integer userType) {
        this.userType = userType;
    }
    public Blob getImage() {
        return this.image;
    }
    
    public void setImage(Blob image) {
        this.image = image;
    }
    public Clob getResume() {
        return this.resume;
    }
    
    public void setResume(Clob resume) {
        this.resume = resume;
    }
}
 
如何使用:
 
package org.hibernate.dao;
import org.hibernatetest.base.HibernateSessionFactory;
import org.hibernatetest.bean.TuserBlob;
import java.sql.*;
import net.sf.hibernate.*;
import java.io.*;

public class TuserBlobDAO {
 public void addTUserBlob(TuserBlob tuserBlob) {
  try {
   Session session = HibernateSessionFactory.getSession();
   Transaction tx = session.beginTransaction();
   session.save(tuserBlob);
   tx.commit();
  } catch (Exception ex) {
   System.out.println(ex.toString());
  }
 }
 public void getTUserBlob(int id,String path) {
  try {
   Session session = HibernateSessionFactory.getSession();
   TuserBlob user = (TuserBlob)session.load(TuserBlob.class, new Integer(id));
   
   Clob resume = user.getResume();
   
   //通过Clob.geSubString()方法获取Clob字段
   System.out.println(
   
     "User resume-->"+
     resume.getSubString(1, (int)resume.length())
   );
   
   Blob image = user.getImage();
   
   //通过Blob.getBinaryStream()方法获得2进制流
   InputStream is = image.getBinaryStream();
   
   
   
   FileOutputStream fos = new FileOutputStream(path);
   
   byte[] buf = new byte[102400];
   
   int len;
   while((len = is.read(buf))!= -1){
    
    fos.write(buf,0,len);
    
   }
   
   fos.close();
   is.close();
   
   
   
  } catch (Exception ex) {
   System.out.println(ex.toString());
  }
 }
}

servlet调用此文件:
 
package org.hibernatetest.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.dao.TuserBlobDAO;
import java.io.*;
import org.hibernatetest.bean.TuserBlob;
import net.sf.hibernate.*;
import java.sql.*;

public class TUserBlobServlet extends HttpServlet {
 /**
  * Constructor of the object.
  */
 public TUserBlobServlet() {
  super();
 }
 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  doPost(request,response);
 }
 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  * 
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  TuserBlob TUserBlob = new TuserBlob();
  
  TUserBlob.setName("lisi001");
  
  TUserBlob.setAge(new Integer(35));
  
  InputStream imageis =this.getServletContext().getResourceAsStream("/images/mm1.jpg");
  
  
  Blob image = Hibernate.createBlob(imageis);
  
  TUserBlob.setImage(image);
  
  Clob resume = Hibernate.createClob("hi,This is a test!");
  
  TUserBlob.setResume(resume);
  
  //new TuserBlobDAO().addTUserBlob(TUserBlob);
  
  String path = "D:\\workspace\\hibernatetest\\WebRoot\\images\\outimage2.jpg";
  
  new TuserBlobDAO().getTUserBlob(2, path);
  
  System.out.println("It's OK!");
  
 }
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occure
  */
 public void init() throws ServletException {
  // Put your code here
 }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值