Since you're asking for a way represent a database record in memory as a byte[].
If I was in your position, I would first do a simple modelling, by creating a java class which can represent the content of the data base record.
For example:
A database record: {id, firstName, lastName} I would simply create a java class as a model like this:
public class Contact {
private long id;
private String firstName;
private String lastName;
// add getters and setters
}
Now when you do a database query and you have one or more records, you can create a new instance of this model for every record and set the content of the model instance from the records you have.
Contact contact = new Contact();
contact.setFirstName("The first name from the database record");
//And so on.
Now to convert a model instance into a byte[]
ByteArrayOutputStream arrOutStream = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(arrOutStream);
out.writeObject(contact);
byte[] bytes = arrOutStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
And to read that object back from the byte[]
byte[] bytesToRead;
ByteArrayInputStream arrInStream = new ByteArrayInputStream(bytesToRead);
try {
ObjectInputStream objectInStream = new ObjectInputStream(arrInStream);
contact = (Contact) objectInStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
Now since you have the model you can put it back into your database.
If you need to do this for multiple records from the database into a single byte[], you can simply create a new model that contains a list of contacts:
class Contacts {
List<Contact> contactsList;
}
Instead of serializing every record into a byte[], you can just create one instance of the Contacts model, and add as much contacts inside, then do the serialization only once for the Contacts instance.