1. 程式人生 > >深入淺出Hibernate之向Mysql插入BLOB,CLOB資料

深入淺出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
 } }

相關推薦

深入淺出HibernateMysql插入BLOB,CLOB資料

轉自:http://blog.chinaunix.net/uid-1718634-id-2821233.html mysql version 5.0 database name:sample 資料表DDL:  create table `sample`.`

JAVAMysql插入億級別資料---測評

利用JAVA向Mysql插入一億數量級資料—效率測評       前景:這幾天研究mysql優化中查詢效率時,發現測試的資料太少(10萬級別),利用 EXPLAIN 比較不同的 SQL 語句,不能夠得到比較有效的測評資料,大多模稜兩可,不敢通過這些資料下

mysql 插入漢字時報錯 Incorrect string value: 'xE6x9BxB9xE5x86xAC...' for col....

str 使用 需要 memento set like 好習慣 address 數據 Incorrect string value: ‘\xE6\x9B\xB9\xE5\x86\xAC...‘ for column ‘realname‘ at row 1 該情況一般是由數據

Linux下TomcatMySQL插入數據中文亂碼解決辦法

中文亂碼解決辦法Linux下Tomcat向MySQL插入數據中文亂碼解決辦法 一、問題 在windows上面使用eclipse開發的項目在windows上面運行一切正常,部署到騰訊雲時出現向MySQL數據庫中插入數據是中文亂碼 二、解決辦法 1、嘗試一直接在linux上面使用insert語句插入中文,正常2、

mysql插入表中的中文顯示為亂碼或問號的解決方法,親測有用!!

重新啟動 重新 安裝 進入 今天 ext database 技術 arc   今天在做ssh的博客項目時發現mysql數據庫中的中文顯示為問號,網上查閱了很多資料,都不是很全,所以我總結一下,供大家參考和自己復習。   1.我的計算機配置: windows系統(linux沒

(轉)javaMySQL插入當前時間的四種方式和java時間日期格式化的幾種方法(案例說明)

轉載地址  https://www.cnblogs.com/zhaotiancheng/p/6413067.html 資料庫操作經常會用到時間,例如start_time,end_time,(在資料庫中是datetime型別,) 對應關係 mys

mysql 插入中文數值報錯

報錯:Error 1366: Incorrect string value: '\xE6\xB5\x8B\xE8\xAF\x95' for column 'description' at row 1 原因是資料庫欄位沒有設定編碼為utf8而是預設的lanti (1)查看錶

如何通過 Mybatis Mysql 插入Date 或者DateTime

MyBatis3做資料持久層,在欄位中有Date和DateTime型別,在插入資料時只要將實體的屬性設定成Timestamp就會對應mysql的DateTime型別,Date會對應mysql的Date

記錄 SpringMVC+Mybatis環境 和 Struts + Hibernate環境 操作mysql存取BLOB資料

SpringMVC+Mybatis環境 和 Struts + Hibernate環境 操作mysql存取BLOB資料 請求流程中的報文需要儲存備用,但有的報文過長,在存MySQL時選擇用BLOB型別 1. 在SpringMVC+Mybatis環境下,直接設定對應的Entity中對

javamysql插入時間,時間日期格式化

java向MySQL插入當前時間的幾種方式和java時間日期格式化的幾種方法:(資料參考網路資源) java向MySQL插入當前時間的幾種種方式 第一種:將java.util.Date型別的時間轉成mysql資料庫識別的java.sql.Date型別時間

mysql插入資料,避免主鍵衝突報錯 duplicate key問題

在進行對資料庫進行資料插入的時候,往往因為重複插入,導致主鍵重複,導致程式報錯,duplicate key,其實只要邊插入變更新就行了,你的sql語句可能是這樣寫的: sql = "insert into simtable values(%s,%s,%s,

servlet mysql 插入中文,在mysql 查詢時發現中文是亂碼

資料庫連線串中指定編碼  url ="jdbc:mysql://localhost:3306/dlmp?useUnicode=true&characterEncoding=utf-8";    將mysql 的客戶端查詢結果集設定編碼   set chara

java程式mysql插入中文變問號

這個問題我已經遇到過很多次,每次都是各種不同的問題,都花了很長時間去解決,這次總結一下: 1、如果在頁面中文顯示亂碼,則在jsp頁面的編碼設定問題上藥注意了,在第一行新增<%@page contentType="text/html" pageEncoding="ut

使用JavaMySQL插入datetime,防止時分秒資訊丟失

問題 使用java.util.Date無法直接插入MySQL,似乎 必須使用java.sql.Date 如果在MySQL中使用timestamp(時間戳),所能表示的時間有限 將java.util.

C#MySql插入資料的時候中文變為亂碼

基本上是編碼問題,找了很久後來發現直接在資料庫的連線字串上寫:charset=utf8; 就可以解決了。 如:  charset=utf8;******;User Id=******;password=******;Database=******;

mybatismysql插入datetime和date的區別

MyBatis3做資料持久層,在欄位中有Date和DateTime型別,在插入資料時只要將實體的屬性設定成Timestamp就會對應mysql的DateTime型別,Date會對應mysql的Date型別。 在MyBatis對映檔案中要表明對映型別。 [htm

javamysql讀寫clob

package com.xiyou;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import ja

深入淺出HibernateDiscriminator的使用

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN""http://hibernate.sourceforge

『PHP學習筆記』系列八:MySQL資料庫中新增資料

資料表結構: 資料表原有資料: 向MySQL資料庫寫入資料:  INSERT INTO 語句通常用於向 MySQL 表新增新的記錄: INSERT INTO table_name (column1, column2, column3,...) VALUES

struts框架問題五值棧中儲存資料

5. 問題五: 向值棧儲存資料 (主要針對root棧) > valueStack.push(Object obj); * push方法的底層呼叫root物件的push方法(把元素新增到0位置) > valueStack.set(String key, Object