Showing posts with label JDBC. Show all posts
Showing posts with label JDBC. Show all posts

Thursday, 1 August 2013

How to save java objects into database in java?

Saving Java objects into database and read it back from database using JDBC


Question:- How we can write binary objects into a database table, for that what type of data type should we use for the creation of database tables?

To Map an object with relational databases and vice versa is always a difficult task.
Very good solutions for that are serialize each Java object using the object stream and preserve the result into a database as a binary blob. As this is a valid scenario and the JDBC explicitly supports to perform this.

Questions: - What is Blob data type?

Answer:-

Binary large object or basic large object: - Large object data types store data ranging in size from 0 bytes to 2 GB. A BLOB is a collection of binary data stored as a single entity in a database. This data type can store binary data larger than VARBINARY (32K limit). Blobs are typically any objects, images, audio, other multimedia objects or other types of business or application-specific data. A BLOB is a varying-length binary string that can be up to 2,147,483,647 characters long.


For storing java objects into the database we can use BLOB datatype in the table.We can create a table using below CREATE TABLE command in MYSQL database.
Table Structure for MySql Database:-

CREATE TABLE persist_java_objects (
object_id int(14) NOT NULL auto_increment,
object_name varchar(30) default NULL,
java_object blob,
PRIMARY KEY  (object_id)
)


System Requirements:-

jdk1.5 and above(I am using jdk1.7)
Eclipse Editor or other(I am using Eclipse Helios).

Required Jars:-

mysql-connector-java-5.0.4-bin.jar


Sample Example to save a List of Objects into database and read back from database :-




SaveObject2Database.java

package com.gaurav.persistjavaobjects;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SaveObject2Database {

            /** This method will help to get mysql connection from database*/   
            private static Connection getConnection() throws Exception {
                        String driver = "com.mysql.jdbc.Driver";
                        String url = "jdbc:mysql://localhost:3306/test";
                        String username = "root";
                        String password = "root";
                        Class.forName(driver);
                        Connection con = DriverManager.getConnection(url, username, password);
                        return con;
            }

                    /** This method will help to convert any object into byte array*/            
                   private static byte[] convertObjectToByteArray(Object obj) throws IOException {
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                        objectOutputStream.writeObject(obj);
                        return byteArrayOutputStream.toByteArray();
            }


                        /** This method will help to save java objects into database*/            
                         private static long saveBlob(Connection con, Object javaObject2Persist) {

                        byte[] byteArray = null;
                        PreparedStatement preparedStatement = null;
                        String SQLQUERY_TO_SAVE_JAVAOBJECT = "INSERT INTO persist_java_objects(object_name, java_object) VALUES (?, ?)";
                        int persistObjectID = -1;
                        try {

                                    byteArray = convertObjectToByteArray(javaObject2Persist);
                                    preparedStatement = con.prepareStatement(
                                                            SQLQUERY_TO_SAVE_JAVAOBJECT,
                                                            PreparedStatement.RETURN_GENERATED_KEYS);
                                    preparedStatement.setString(1, javaObject2Persist.getClass()
                                                            .getName());
                                    preparedStatement.setBytes(2, byteArray);
                                    preparedStatement.executeUpdate();

                                    System.out
                                                            .println("Query - "
                                                                                    + SQLQUERY_TO_SAVE_JAVAOBJECT
                                                                                    + " is successfully executed for Java object serialization ");

                                    //Trying to get the Generated Key
                                    ResultSet rs = preparedStatement.getGeneratedKeys();

                                    if (rs.next()) {
                                                persistObjectID = rs.getInt(1);
                                                System.out
                                                                        .println("Object ID while saving the binary object is->"
                                                                                                + persistObjectID);
                                    }

                                    preparedStatement.close();
                        } catch (SQLException e) {
                                    e.printStackTrace();
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }
                        return persistObjectID;
            }

/** This method will help to read java objects from database*/               
private static byte[] getBlob(Connection con, long objectId) {
                        String SQLQUERY_TO_READ_JAVAOBJECT= "SELECT java_object FROM persist_java_objects WHERE object_id = ?;";
                        PreparedStatement pstmt = null;
                        ResultSet resultSet = null;
                        Blob blob = null;
                        byte[] bytes = null;

                        try {
                                    pstmt = con.prepareStatement(SQLQUERY_TO_READ_JAVAOBJECT);
                                    System.out.println("Reading the saved Object from the database where the object Id is:->" + objectId);
                                    pstmt.setLong(1, objectId);

                                    resultSet = pstmt.executeQuery();
                                    while (resultSet.next()) {
                                                blob = resultSet.getBlob(1);
                                    }
                                    bytes = blob.getBytes(1, (int) (blob.length()));

                        } catch (SQLException e) {
                                    e.printStackTrace();
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }
                        return bytes;
            }

            @SuppressWarnings("unchecked")
            public static void main(String args[]) throws Exception {
                        Connection connection = null;
                        byte[] retrievedArrayObject = null;
                        try {
                                    connection = getConnection();

                                    List<Object> listToSaveInDB = new ArrayList<Object>();
                                    listToSaveInDB.add(new Date());
                                    listToSaveInDB.add(new String("KUMAR GAURAV"));
                                    listToSaveInDB.add(new Integer(55));

                                    long persistObjectID = saveBlob(connection, listToSaveInDB);
                                    System.out.println(listToSaveInDB + " Object is saved sucessfully");

                                    retrievedArrayObject = getBlob(connection, persistObjectID);

                                    ObjectInputStream objectInputStream = null;
                                    if (retrievedArrayObject != null)
                                                objectInputStream = new ObjectInputStream(
                                                                        new ByteArrayInputStream(retrievedArrayObject));

                                    Object retrievingObject = objectInputStream.readObject();

                                    List<Object> dataListFromDB = (List<Object>) retrievingObject;
                                    for (Object object : dataListFromDB) {
                                                System.out.println("Retrieved Data is :->" + object.toString());
                                    }

                                    System.out
                                                            .println("Successfully retrieved java Object from Database");

                        } catch (Exception e) {
                                    e.printStackTrace();
                        } finally {
                                    connection.close();
                        }
            }
}

Result:->

Query - INSERT INTO persist_java_objects(object_name, java_object) VALUES (?, ?) is successfully executed for Java object serialization
Object ID while saving the binary object is->13
[Fri Aug 02 07:17:26 IST 2013, KUMAR GAURAV, 10055] Object is saved sucessfully
Reading the saved Object from the database where the object Id is:->13
Retrieved Data is :->Fri Aug 02 07:17:26 IST 2013
Retrieved Data is :->KUMAR GAURAV
Retrieved Data is :->10055
Successfully retrieved java Object from Database
 
Table Status after insertion java objects into database:-



How to save an Image and read back from database in Java?

Example to insert an image into the database and read from database




The setBinaryStream() method is used to set Binary information into the parameterIndex. This method is available in the PreparedStatement interface.

  • Public void setBinaryStream(int paramIndex, InputStream in) throws SQLException
  • Public void setBinaryStream(int paramIndex, InputStream in, int length) throws SQLException

For storing an image into the database we can use BLOB datatype in the table.We can create a table using below CREATE TABLE command in MYSQL database.

Table Structure for MySql Database:-

CREATE TABLE persist_java_objects (
object_id int(14) NOT NULL auto_increment,
object_name varchar(30) default NULL,
java_object blob,
PRIMARY KEY  (object_id)
)


System Requirements:-

jdk1.5 and above(I am using jdk1.7)
Eclipse Editor or other(I am using Eclipse Helios).

Required Jars:-

mysql-connector-java-5.0.4-bin.jar

Sample Example to save an image into database and read back from database and open with default image viewer or browser:-



package com.gaurav.persistjavaobjects;

import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SaveImage2Database {

            private static Connection getConnection() throws Exception {
                        String driver = "com.mysql.jdbc.Driver";
                        String url = "jdbc:mysql://localhost:3306/test";
                        String username = "root";
                        String password = "root";
                        Class.forName(driver);
                        Connection con = DriverManager.getConnection(url, username, password);
                        return con;
            }

            /** This method will help to save an image object into database */
            private static long saveImageFile(Connection con, String fileName) {

                        PreparedStatement preparedStatement = null;
                        String SQLQUERY_TO_SAVE_JAVAOBJECT = "INSERT INTO persist_java_objects(object_name, java_object) VALUES (?, ?)";
                        int persistObjectID = -1;
                        try {

                                    File file = new File(fileName);
                                    FileInputStream fileInputStream = new FileInputStream(file);

                                    // This will help to request for returning the generated key
                                    preparedStatement = con.prepareStatement(
                                                            SQLQUERY_TO_SAVE_JAVAOBJECT,
                                                            PreparedStatement.RETURN_GENERATED_KEYS);

                                    preparedStatement.setString(1, fileName.getClass().getName());
                                    preparedStatement.setBinaryStream(2, fileInputStream,
                                                            (int) file.length());
                                    preparedStatement.executeUpdate();

                                    System.out
                                                            .println("Query - "
                                                                                    + SQLQUERY_TO_SAVE_JAVAOBJECT
                                                                                    + " is successfully executed for Java object serialization ");

                                    // Trying to get the Generated Key
                                    ResultSet rs = preparedStatement.getGeneratedKeys();

                                    if (rs.next()) {
                                                persistObjectID = rs.getInt(1);
                                                System.out
                                                                        .println("Object ID while saving the binary object is->"
                                                                                                + persistObjectID);
                                    }

                                    preparedStatement.close();
                        } catch (SQLException e) {
                                    e.printStackTrace();
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }
                        return persistObjectID;
            }

            /** This method will help to read an image object from database */
            private static void getBlob(Connection con, long objectId) {
                        String SQLQUERY_TO_READ_JAVAOBJECT= "SELECT java_object FROM persist_java_objects WHERE object_id = ?;";
                        PreparedStatement pstmt = null;
                        ResultSet resultSet = null;
                        Blob blobData = null;

                        try {
                                    pstmt = con.prepareStatement(SQLQUERY_TO_READ_JAVAOBJECT);
                                    System.out.println("Object Id is:->" + objectId);
                                    // Setting the same object id which we got during image object save
                                    pstmt.setLong(1, objectId);

                                    resultSet = pstmt.executeQuery();

                                    while (resultSet.next()) {
                                                blobData = resultSet.getBlob("java_object");

                                                InputStream inputStream = blobData.getBinaryStream();

                                                int size = inputStream.available();

                                                FileOutputStream out = new FileOutputStream(
                                                                        "c://Image//Thank.gif");

                                                byte b[] = new byte[size];
                                                inputStream.read(b);
                                                out.write(b);
                                                out.close();
                                    }

                        } catch (SQLException e) {
                                    e.printStackTrace();
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }

            }

            public static void main(String args[]) throws Exception {
                        Connection connection = null;

                        try {
                                    connection = getConnection();
                                    String fileName = "G://GIF//ThankYou.gif";
                                    long persistObjectID = saveImageFile(connection, fileName);
                                    System.out.println("Image is saved sucessfully");

                                    // Calling the method to read the image from database.
                                    getBlob(connection, persistObjectID);

                                    System.out
                                                            .println("Successfully retrieved java Object from Database");

                                    String fileNameAfterRead = "c://Image//Thank.gif";
                                    /**

                                     * This piece of code will help to open the image file in default

                                     * image viewer.

                                     */
                                   File fileName2Open = new File(fileNameAfterRead);
                                   Desktop desktop = Desktop.getDesktop();
                                   desktop.open(fileName2Open);
                                   System.out.println("File Opened successfully at the first time.");

                                    /**

                                     * This piece of code will help to open the image file in default

                                     * browser.

                                     */
                                    String[] executionCommands = { "cmd.exe", "/c", "start",
                    "\"ThankYouImage\"", "\"" + fileNameAfterRead + "\"" };
                                    Process process = Runtime.getRuntime().exec(executionCommands);
                                    process.waitFor();
                                    System.out.println("File Opened successfully at the second time.");

                        } catch (Exception e) {
                                    e.printStackTrace();
                        } finally {
                                    connection.close();
                        }
            }
}

Result:-

Query - INSERT INTO persist_java_objects(object_name, java_object) VALUES (?, ?) is successfully executed for Java object serialization
Object ID while saving the binary object is->6
Image is saved sucessfully
Object Id is:->6
Successfully retrieved java Object from Database
File Opened successfully at the first time.
File Opened successfully at the second time.

Table Status after image insertion:-