Lesson - 68 : Hibernate - Insert & Reading image using XML and Annotation Config

Опубликовано: 29 Сентябрь 2024
на канале: Sada Learning Hub
953
9

Hibernate – Insert and Reading Image Using Hibernate:
->An image can not be inserted or retrieved directly using hibernate. To do inserting or reading an image operation that image must be transfer to hibernate in the form of or as a part of pojo class object.
->To set an image to a pojo class object. Pojo class should contain a property of type BLOB(java.sql.Blob).
->To set an image to a pojo class object first we need to read binary data of that image then we need to create a java.sql.Blob object and then we need to set java.sql.Blob object to pojo class object.
->To store binary data of an image in database the clumn of a table should be of blob type(BLOB-BinaryLargeOBject).
To convert an image file into a java.sql.Blob object, we need to follow the below steps.
1. Create a File object (java.io.File object) for an image file.
2. Find size of the image file.
3. Create a byte[] with the size of the image.
4. Create a java.io.FileInputStream object for an image file.
5. Read the binary data of image file and store it in a byte[].
6. Create a Blob for byte[].
7. Finally set blob object to pojo class object.
Sample Code : File file = new File("E:\\Desktop items\\Images\\App-1Hierarchy.png");
int length = (int)file.length();
byte b[] = new byte[length];
FileInputStream fis = new FileInputStream(file);
fis.read(b);
Blob photo = Hibernate.createBlob(b);
The following are the steps to required to read an image
1. Read a pojo class object from a database using hibernate.
2. Read java.sql.Blob object from pojo object.
3. Read binary data from Blob object.
4. create a FileOutputStream object for writing or creating a new image file.
5. Read binary data from InputStreamObject and write it into new image file.
Sample Code : InputStream in = blb.getBinaryStream();
FileOutputStream fos= new FileOutputStream("E:\\Desktop items\\Images\\App-1Hierarchy.png");
int k;
while((k=in.read())!=-1){
fos.write(k);
}
fos.close();

Hibernate Examples Project Github Link : https://github.com/SadaLearningHub1/H...