Store Java objects in Oracle databases

Source: Internet
Author: User

Object Persistence means that this object can be permanently saved. The persistence here is not only the object itself, but also its attributes and other dependent classes. Objects can be persisted to files or databases. Here I will only describe how to store objects in a database. It happens that the Oracle database provides us with such convenience.

In Oracle, a blog field type is used to store a large amount of binary data. We use this field to store object information. First, create a test table:
Create Table testblob
(
Name varchar2 (50) not null,
Content blob not null,
ID number (8) Not null
) Alter table testblob
Add constraint idfortest primary key (ID );

Only three fields are used, where ID is an attribute and content is the field of the object to be stored.

Let's take a look at the objects we want to store:

Import java. Io. serializable;
Import java. util. date;
Import java. util. List;

Public class testobject implements serializable {
 
Private Static final long serialversionuid = 4558876142427402513l;
/**
* @ Param ARGs
*/
Private string name;
Private string password;
Private date;
Private list <city> citylist;
 
Public list <city> getcitylist (){
Return citylist;
}
Public void setcitylist (list <city> citylist ){
This. citylist = citylist;
}
Public date getdate (){
Return date;
}
Public void setdate (date ){
This. Date = date;
}
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
Public String GetPassword (){
Return password;
}
Public void setpassword (string password ){
This. Password = password;
}
}

Remember to implement the serializable interface. We can see that this is an object containing the string, date, and list types. To increase the complexity of the test, our list is another object (city) is as follows:

Import java. Io. serializable;

Public class city implements serializable {
Private Static final long serialversionuid = 4558876109402513l;
Private string name;
Private string code;
Public String getcode (){
Return code;
}
Public void setcode (string code ){
This. Code = code;
}
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
}

The city object includes the city name and area code. The following are the main applications.

Import java. Io. bufferedinputstream;
Import java. Io. bytearrayinputstream;
Import java. Io. bytearrayoutputstream;
Import java. Io. inputstream;
Import java. Io. objectinputstream;
Import java. Io. objectoutputstream;
Import java. Io. outputstream;
Import java. SQL. connection;
Import java. SQL. drivermanager;
Import java. SQL. resultset;
Import java. SQL. statement;
Import java. util. arraylist;
Import java. util. date;
Import java. util. List;

Import oracle. SQL. Blob;

Public class test {

Public static void main (string [] ARGs ){
// Create a test object
City Beijing = New City ();
Beijing. setname ("Beijing ");
Beijing. setcode ("010 ");

City Shanghai = New City ();
Shanghai. setname ("Shanghai ");
Shanghai. setcode ("020 ");

City Tianjin = New City ();
Tianjin. setname ("Tianjin ");
Tianjin. setcode ("021 ");

List <city> citylist = new arraylist <city> ();
Citylist. Add (Beijing );
Citylist. Add (Shanghai );
Citylist. Add (Tianjin );

Testobject OBJ = new testobject ();
OBJ. setname ("yangsq ");
OBJ. setpassword ("111 ");
OBJ. setdate (new date ());
OBJ. setcitylist (citylist );

Try {
// Save the object to the Blob Field
Bytearrayoutputstream byteout = new bytearrayoutputstream ();
Objectoutputstream outobj = new objectoutputstream (byteout );
Outobj. writeobject (OBJ );
Final byte [] objbytes = byteout. tobytearray ();

Class. forname ("oracle. JDBC. Driver. oracledriver ");
Connection con = drivermanager. getconnection (
"JDBC: oracle: thin :@***. ***. ***. * **: 1521: ***** "," yangsq "," yangsq ");
Con. setautocommit (false );
Statement ST = con. createstatement ();

St.exe cuteupdate ("insert into testblob (ID, name, content) values (1, 'test1', empty_blob ())");
Resultset rs = st.exe cutequery ("select content from testblob where id = 1 for update ");

If (Rs. Next ()){
Blob blob = (BLOB) Rs. getblob ("content ");
Outputstream outstream = blob. getbinaryoutputstream ();
Outstream. Write (objbytes, 0, objbytes. Length );
Outstream. Flush ();
Outstream. Close ();
}

Byteout. Close ();
Outobj. Close ();
Con. Commit ();

// Retrieve the objects in the Blob field and restore them.
Rs = st.exe cutequery ("select content from testblob where id = 1 ");
Blob inblob = NULL;
If (Rs. Next ()){
Inblob = (BLOB) Rs. getblob ("content ");
}
Inputstream is = inblob. getbinarystream ();
Bufferedinputstream input = new bufferedinputstream (is );

Byte [] buff = new byte [inblob. getbuffersize ()];
While (-1! = (Input. Read (buff, 0, Buff. Length )));

Objectinputstream in =
New objectinputstream (
New bytearrayinputstream (
Buff ));
Testobject W3 = (testobject) in. readobject ();
System. Out. println (w3.getname ());
System. Out. println (w3.getpassword ());
System. Out. println (w3.getdate ());

List <city> List = w3.getcitylist ();
For (city City: List ){
System. Out. println (city. getname () + "" + city. getcode ());
}

St. Close ();
Con. Close ();
} Catch (exception ex ){
Ex. printstacktrace ();
System. Exit (1 );
}
}
}

The blue part of the Code creates the object to be stored. Let's look at the red object writing part. It first converts the object into a binary stream. For blob fields, we cannot simply insert during insert. In fact, during insert, for blob fields, we can only insert an empty BLOB Object empty_blob () first (), then, "select content from testblob where id = 1 for update" is performed to update the Blob field. After the result is returned, we only need to write the binary stream of the object.

Outputstream outstream = blob. getbinaryoutputstream ();
Outstream. Write (objbytes, 0, objbytes. Length );

Note that con. setautocommit (false) must be set in the preceding steps; otherwise, an exception is thrown in Oracle.

Next, the green code is to read the object of the Blob field in the database and restore it. We need to know that all operations on BLOB fields are binary, that is, they are binary streams during insertion and binary streams during reading. Then, use the I/O modifier (objectinputstream) to modify it. When I used to learn Java, I felt that its Io was so cumbersome. Now I feel that it is really useful. The following is the output result of the test.

Yangsq
111
Tue Mar 27 12:11:28 CST 2007
Beijing 010
Shanghai 020
Tianjin 021

Note that the buff size must be large enough; otherwise, an exception is thrown. Here, I am using inblob. getbuffersize () is used to set the buff size. This is not a good method, because inblob is generally used. getbuffersize () is 32768, and an exception is likely to occur. Therefore, it is recommended that you set this size or set the system Runtime (Fortunately, Java provides the runtime setting of the array length ).

The above is the result of my own research, of course, the knowledge and dedication of netizens are indispensable. The following is the blog of a netizen.

To:

1. Create a record and insert BLOB Data
1.1 when creating a record, use the Oracle function to insert an empty blob. Assume that field a is of the Blob type:
Insert xxxtable (a, B, c) values (empty_blob (), 'xxx', 'yyyy ')
1.2 query the inserted record and update blob. Before the query, set an attribute of connection:
Conn. setautocommit (false); if this step is missing, exceptions such as fetch out of sequence may occur.
1.3 query the inserted record, followed by "for update", as shown below:
Select a from xxxtable Where xxx = 999 for update. If for update is missing, the row containing the lob value is not locked.

Exception
1.4 obtain and update the blob from the queried blob field. The Code is as follows:
Blob blob = (BLOB) Rs. getblob ("");
Outputstream OS = blob. getbinaryoutputstream ();
Bufferedoutputstream output = new bufferedoutputstream (OS );

You can use the output. Write method to write the content to the output file. For example, we write a file into this field:
Bufferedinputstream input = new bufferedinputstream (new file ("C: // hpwave. log"). tourl (). openstream ());
Byte [] buff = new byte [2048]; // Buffer Used for file writing
Int bytesread;
While (-1! = (Bytesread = input. Read (buff, 0, Buff. Length ))){
Output. Write (buff, 0, bytesread );
System. Out. println (bytesread );
}
The above Code reads data from input 2 K and then writes it to output.
1.5 after the preceding execution is complete, close output, input, and the queried resultset.
1.6 finally run conn. Commit (); Submit the updated content, and execute conn. setautocommit (true); change back to the connction attribute
2. Modify the record. The method is similar to the above method,
2.1 First Update fields other than blob
2.2 use a similar method in 1.3 to obtain records
2.3 During modification, note the following: blob may be null in the record to be updated by a, so that the value obtained by executing blob. getbinaryoutputstream () may be

Null, close the select record and execute update xxxtable set a = empty_blob () Where xxx again. In this way, an empty blob (not null) is written first, and then

Use the methods in 1.3 and 1.4 to execute the update record. B do not forget to execute setautocommit (false), "for update", and the following conn. Commit.
3. read data from BLOB fields.
3.1 setautocommit () is not required to read records, and select... for update.
3.2 query the output records using the normal select Method
3.3 obtain and read blob from resultset, as shown below:
Blob B _to = (BLOB) Rs. getblob ("");
Inputstream is = B _from.getbinarystream ();
Bufferedinputstream input = new bufferedinputstream (is );
Byte [] buff = new byte [2048];
While (-1! = (Bytesread = input. Read (buff, 0, Buff. Length ))){
// Write data here, for example, in the bufferedoutputstream of the file
System. Out. println (bytesread );
}
The data in blob is retrieved cyclically, written to buff, and then the buff content is written to the desired location.
4. Transmission of BLOB fields between two databases
Similar to the methods 1 and 3 above, get bufferedoutputstream while get bufferedinputstream and read and write data. Note that

Connection needs to execute conn. setautocommit (false); and add "for update" and the final commit () when obtaining the record ();

To sum up the above methods, it is simply to first create an empty blob, then obtain its bufferedoutputstream for writing, or obtain bufferedinputstream for reading.

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.