Use hibernate to read and write data of the Oracle blob/clob type

Source: Internet
Author: User

Environment: eclipse3.1 + hibernate2 + Oracle 10g
Note: In this example, eclipse3.1 is used to read and write blob/clob data in Oracle through a Java project.
1. Create a new table in the Oracle database named bigdata. The SQL statement is as follows:
Create Table bigdata (ID number not null, image blob, resume clob); // create a table
Alter table bigdata add (constraint bigdata_pk primary key (ID) using index); // modify the ID to the primary key:

2. Create a New Java project in eclipse named hibernatesample. You can import the JAR file to be imported in the project as needed.
Create a source folder SRC, create a new package under SRC, name it bigdataaccess, and create a class under the package named datamodel. java. The content is as follows:
Package bigdataaccess;

Import java. SQL. Blob;
Import java. SQL. clob;

Public class datamodel {
Long ID;

Blob image;

Clob resume;

Public long GETID (){
Return ID;
}

Public void setid (long ID ){
This. ID = ID;
}

Public blob getimage (){
Return image;
}

Public void setimage (BLOB image ){
This. Image = image;
}

Public clob getresume (){
Return resume;
}

Public void setresume (clob resume ){
This. Resume = resume;
}
}

2. Create a class named hibernateutil. Java under the bigdataaccess package to manage the session. The source code is as follows:
Package bigdataaccess;

Import net. SF. hibernate .*;
Import net. SF. hibernate. cfg. configuration;

Public class hibernateutil {
Private Static sessionfactory;

Public static final threadlocal session = new threadlocal ();
Static {
Try {
// Instantiate a sessionfactory object
// System. Out. println ("Create a sessionfactory through the static module ");
Sessionfactory = new configuration (). Configure ()
. Buildsessionfactory ();
} Catch (hibernateexception ex ){
Throw new runtimeexception ("configuration problem :"
+ Ex. getmessage (), Ex );
}
}
Public static session currentsession () throws hibernateexception {
Session S = (Session) Session. Get ();
// When the original session is empty or closed, create a new session.
If (S = NULL |! S. isopen ()){
S = sessionfactory. opensession ();
Session. set (s );
}
Return S;
}

Public static void closesession () throws hibernateexception {
Session S = (Session) Session. Get ();
If (s! = NULL ){
S. Close ();
}
}
}

2. Create the biging file bigdataaccess. HBM. xml under the bigdataaccess package. The content is as follows:
<? XML version = "1.0"?>
<! Doctype hibernate-mapping public
"-// Hibernate/hibernate mapping DTD 2.0 // en"
Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd>

<Hibernate-mapping>
<Class name = "bigdataaccess. datamodel" table = "bigdata">
<ID name = "ID" type = "long" column = "ID">
<Generator class = "increment"/>
</ID>
<Property name = "image" type = "Java. SQL. Blob" column = "image"/>
<Property name = "resume" type = "Java. SQL. clob" column = "resume"/>
</Class>
</Hibernate-mapping>
3. Create a New hibernate configuration file under the src directory. The content of hibernate. cfg. XML is as follows:
<? XML version = '1. 0' encoding = 'utf-8'?>
<! Doctype hibernate-configuration public "-// hibernate/hibernate configuration DTD // en"
Http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd>

<Hibernate-configuration>
<Session-factory>
<Property name = "hibernate. Connection. driver_class"> oracle. JDBC. Driver. oracledriver </property>
<Property name = "hibernate. Connection. url"> JDBC: oracle: thin: @ localhost: 1521: orcl </property>
<Property name = "hibernate. Connection. username"> Work </property>
<Property name = "hibernate. Connection. Password"> caecaodb </property>
<Property name = "hibernate. show_ SQL"> true </property>
<Property name = "dialect"> net. SF. hibernate. dialect. oracledialect </property>
<! -- This sentence must be added. Otherwise, an error will be reported, because oracle JDBC does not allow stream operations to be performed in batches, so disable -->
<Property name = "hibernate. JDBC. batch_size"> 0 </property>
<Mapping Resource = "bigdataaccess/bigdataaccess. HBM. xml"/>
</Session-factory>
</Hibernate-configuration>
4. Create a class with the main () function under the bigdataaccess package and name it hibernatetest. java. The source code is as follows:
Package bigdataaccess;
// Note that the correct package must be imported

Public class hibernatetest {

Public hibernatetest () throws hibernateexception, sqlexception, ioexception {
Doit ();
}

Public static void main (string [] ARGs) throws hibernateexception,
Sqlexception, ioexception {
New hibernatetest ();

}

Public void doit () throws hibernateexception, sqlexception, ioexception {

// Blog, clob data read/write --------- write

/*
* The Oracle blob/clob field itself has a cursor (cursor ),
* JDBC uses a cursor to operate the Blob/clob field. Before the Blob/clob field is created,
* The cursor handle cannot be obtained. Therefore, you must first create an empty blob/clob field, then obtain the cursor from the empty blob/clob field, and then write the data to be saved.
*/
System. Out. println ("Write Data ");
Session session = hibernateutil. currentsession ();
Transaction Tx = session. begintransaction ();

Datamodel info = new datamodel ();
Info. setimage (hibernate. createblob (New byte [1]);
Info. setresume (hibernate. createclob (""); // The parameter here is a space
Session. Save (Info );
Session. Flush (); // force insert
// Use the refresh method to force hibernate to execute select for update
Session. Refresh (Info, lockmode. Upgrade );

// Write the actual content to the blog
Oracle. SQL. Blob blob = (Oracle. SQL. Blob) info. getimage ();
Fileinputstream imgis = new fileinputstream ("D: // image.jpg"); // put an image.jpg file under the D:/root directory.
Outputstream out = blob. getbinaryoutputstream ();
Byte [] Buf = new byte [1, 10240];
Int Len;
While (LEN = imgis. Read (BUF)> 0 ){
Out. Write (BUF, 0, Len );
}
Imgis. Close ();
Out. Close ();

// Write actual content to clob
Oracle. SQL. clob = (Oracle. SQL. clob) info. getresume ();
Writer writer = clob. getcharacteroutputstream ();
Writer. Write ("this is my resume ");
Writer. Close ();

Session. Save (Info );
TX. Commit ();
// Read the data written into the database
System. Out. println ("read data ");
Datamodel info1 = (datamodel) session
. Load (datamodel. Class, new long (1 ));
Clob resume = info1.getresume ();
System. Out. println ("resume ="
+ Resume. getsubstring (1, (INT) resume. Length ()));

Blob IMG = info1.getimage ();
Inputstream is = IMG. getbinarystream ();
Fileoutputstream Fos = new fileoutputstream ("D: // outimage.jpg"); // read to D:/outimage.jpg
Byte [] buf1 = new byte [10240];
Int len1;
While (len1 = is. Read (buf1 ))! =-1 ){
FOS. Write (buf1, 0, len1 );
}
FOS. Close ();
Is. Close ();
Session. Close ();
}

Right-click hibernatetest. Java and run it as a Java application. When you query the bigdata table, a new record is added. D:/has a file named outimage.jpg, indicating that it is successful.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.