Jdbc+hibernate writes BLOB data to Oracle

Source: Internet
Author: User
Tags commit count empty file size flush getmessage insert
oracle| Data Oracle's BLOB field is special, he is much better than a long field, and can be used to save binary data, such as pictures.

It is very different to write a BLOB field and write to another type of field, because the BLOB itself has a cursor, you must manipulate the BLOB using cursor, so you must obtain cursor before writing the Blob, So how do you get the cursor of a blob?

This requires you to first insert a empty blob, which will create a blob of cursor, and then you can use the cursor of this empty blob to query with SELECT, so that in two steps you get the cursor of the BLOB, Can actually write BLOB data.

Look at the following JDBC demo and write the Oraclejdbc.jar binary to the Content field in the database table Javatest (This is a BLOB field)

Import java.sql.*;
Import java.io.*;
Import oracle.sql.*;
public class Writeblob {

public static void Main (string[] args) {

try {
Drivermanager.registerdriver (New Oracle.jdbc.driver.OracleDriver ());
Connection conn = Drivermanager.getconnection ("Jdbc:oracle:thin: @localhost: 1521:orcl", "Fankai", "Fankai");
Conn.setautocommit (FALSE);

Blob blob = null;

PreparedStatement pstmt = conn.preparestatement ("INSERT into javatest (name,content) VALUES (?, Empty_blob ())");
Pstmt.setstring (1, "Fankai");
Pstmt.executeupdate ();
Pstmt.close ();

pstmt = conn.preparestatement ("Select content from Javatest where name=?") For update ");
Pstmt.setstring (1, "Fankai");
ResultSet RSet = Pstmt.executequery ();
if (Rset.next ()) blob = (BLOB) Rset.getblob (1);

String fileName = "Oraclejdbc.jar";
File F = new file (fileName);
FileInputStream fin = new FileInputStream (f);
SYSTEM.OUT.PRINTLN ("File size =" + fin.available ());

pstmt = conn.preparestatement ("Update javatest set content=?") where name=? ");

OutputStream out = Blob.getbinaryoutputstream ();

int count =-1, total = 0;
byte[] data = new byte[(int) fin.available ()];
Fin.read (data);
Out.write (data);
/*
byte[] data = new byte[blob.getbuffersize ()]; Another way to achieve memory savings
while ((count = fin.read (data))!=-1) {
Total = count;
Out.write (data, 0, count);
}
*/

Fin.close ();
Out.close ();

Pstmt.setblob (1,BLOB);
Pstmt.setstring (2, "Fankai");

Pstmt.executeupdate ();
Pstmt.close ();

Conn.commit ();
Conn.close ();
catch (SQLException e) {
System.err.println (E.getmessage ());
E.printstacktrace ();
catch (IOException e) {
System.err.println (E.getmessage ());
}
}

}

Take a closer look at the example, in three steps:

1. Insert an empty blob

Into Javatest (name,content) VALUES (?, Empty_blob ());

2, get the cursor of the BLOB

Select content from Javatest where name=? for update;

Attention!!! You must add a for update, which locks the row until the row has been modified to ensure no concurrency conflict.

3, update javatest set content=? where name=

Write data to the database with cursor

Here's another thing to remind you:

The JDBC2.0 specification for the JDK1.3 band is imperfect, with only the interface to read the Blob, without the interface to write the Blob, and the JDBC3.0 of the JDK1.4 band is joined by the write Blob interface. You can use the JDBC3.0 interface, or you can use Oracle's JDBC API directly, and I use the Oracle JDBC API in the example above.

In addition, it should be noted that:

Java.sql.Blob

Oracle.sql.BLOB

Note that the case of the BLOB is different. Don't confuse when writing a program.

The following to see how to write with Hibernate, the principle is the same, but also to three steps, but the code is much simpler

This is a Cat object definition

Package Com.fankai;

Import Java.sql.Blob;

public class Cat {
Private String ID;
private String name;
private char sex;
private float weight;
Private Blob image;
Public Cat () {}

Public String GetId () {return ID;}
public void SetId (String id) {this.id = ID;}

Public String GetName () {return name;}
public void SetName (String name) {this.name = name;}

Public Char Getsex () {return sex;}
public void Setsex (char sex) {this.sex = sex;}

public float Getweight () {return weight;}
public void Setweight (float weight) {this.weight = weight;}

Public Blob GetImage () {return image;}
public void SetImage (Blob image) {this.image = image;}
}


This is Cat.hbm.xml.

<?xml version= "1.0"? > >
! DOCTYPE hibernate-mapping SYSTEM "HTTP://HIBERNATE.SOURCEFORGE.NET/HIBERNATE-MAPPING-2.0.DTD" >

<class name= "Com.fankai.Cat" table= "Cat"
The!--jcs-cache usage= "Read-only"/-->
<ID name= "id" unsaved-value= "null"
<generator class= "Uuid.hex"/>
</id>
<property name= "name" Length= "not-null=" true "/"
<property name= "Sex" length= "1" not-null= "true"/>
<property name= "Weight"/>
<property name= "image"/>
</class>

Here is a complete example of using hibernate to write BLOBs, which are much simpler than JDBC, and do not need to write those Oracle-specific SQL:

Package Com.fankai;

Import Java.sql.Blob;
Import net.sf.hibernate.*;
Import oracle.sql.*;
Import java.io.*;

public class Testcathibernate {
public static void Testblob () {
session s = NULL;
byte[] buffer = new BYTE[1];
Buffer[0] = 1;
try {
Sessionfactory SF = Hibernatesessionfactory.getsessionfactory ();
s = sf.opensession ();
Transaction tx = S.begintransaction ();
Cat C = new Cat ();
C.setname ("Robbin");
C.setimage (Hibernate.createblob (buffer));
S.save (c);
S.flush ();
S.refresh (c, Lockmode.upgrade);
Blob blob = (BLOB) c.getimage ();
OutputStream out = Blob.getbinaryoutputstream ();
String fileName = "Oraclejdbc.jar";
File F = new file (fileName);
FileInputStream fin = new FileInputStream (f);
int count =-1, total = 0;
byte[] data = new byte[(int) fin.available ()];
Fin.read (data);
Out.write (data);
Fin.close ();
Out.close ();
S.flush ();
Tx.commit ();

catch (Exception e) {
System.out.println (E.getmessage ());
finally {
if (s!= null)
try {
S.close ();
catch (Exception e) {}
}
}
}


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.