Tuesday, May 31, 2011

JPA: Insert and retrieve clob and blob types


This article describes about the JPA feature for handling clob and blob data types. You will learn the following in this article.
  • @Lob annotation
  • Client code to insert and retrieve the clob/blob types
  • End to End ADFaces application to retrieve the image from database table and display it in web page (Will be completed).

Use Case Description
Persisting and reading the image from database using JPA clob/blob type.

@Lob annotation
By default, TopLink JPA assumes that all persistent data can be represented as typical database data types.
Use the @Lob annotation with a basic mapping to specify that a persistent property or field should be persisted as a large object to a database-supported large object type.
A Lob may be either a binary or character type. TopLink JPA infers the Lob type from the type of the persistent field or property.
For string and character-based types, the default is Clob. In all other cases, the default is Blob.

Example

Below code shows how to use this annotation to specify that persistent field pictureshould be persisted as a Blob.
1
2
3
4
5
6
7
8
9
10
public class Person implements Serializable
{
    @Id
    @Column(nullable = false, length = 20)
    private String name;
    
    @Lob
    @Column(nullable = false)
    private byte[] picture;
}

Client code to insert and retrieve the clob/blob types
Reading a image file and inserting to Database table
Below client code will read the image from a file and persist to Person table in database.

1
2
3
4
5
Person p=new Person();
p.setName("Tom");
p.setSex("male");
p.setPicture(writtingImage("Image location"));// - c:\images\test.jpg
sessionEJB.persistPerson(p);
Retrieving the image from Database table and writing to a file
1
2
3
List<Person> plist=sessionEJB.getPersonFindAll();
Person person=(Person)plist.get(0);   //get a person object
retrieveImage(person.getPicture());   //get picture retrieved from Table
Private method to create byte[] from image file 
1
2
3
4
5
6
7
8
9
10
private static byte[] writtingImage(String fileLocation) {
      System.out.println("file lication is"+fileLocation);
     IOManager manager=new IOManager();
     try {
           return manager.getBytesFromFile(fileLocation);
        } catch (IOException e) { }
        
return null;
}
Private method to read byte[] from database and write to a image file
1
2
3
4
5
6
7
private static void retrieveImage(byte[] b) {
    IOManager manager=new IOManager();
        try {
            manager.putBytesInFile("c:\\webtest.jpg",b);
        } catch (IOException e) {}
}
Related Links
  1. Reading a file into a byte array

No comments :

Post a Comment