Thursday, July 22, 2010

Reading Java Object From Database

import java.io.Serializable;
public class Employee implements Serializable {
    private int Id; 
    private String firstName;
}


PreparedStatement pstmt = conn.prepareStatement(SQL_SELECT_QUERY);
pstmt.setLong(1, key);
ResultSet rs = pstmt.executeQuery();
rs.next();


byte[] buf = rs.getBytes("object_value");


if (buf != null){
ObjectInputStream objectIn = new ObjectInputStream(new      ByteArrayInputStream(buf));
Object object = objectIn.readObject();
Employee emp = (Employee) object;
}


here we can not read directly object from Database, we may get this object in byte stream. 


the ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(buf)); statment will reaturn the object input stream from where we will derived java object by Object object = objectIn.readObject(); statment. 


now once you get java object you know this is the object of Employee type, so you can directly cast this object to Employee class. 

No comments:

Post a Comment