I am having some trouble properly retrieving blob data from my database using java in my JSF 2.0 application. The first problem I am having is on my getter method for the Blob named "file" I get an error saying that "Basic attributes can only be of the following types..." basically saying that I can not return a Blob object. My code looks like what is below. Even with the error my code compiles. I have created a test method (the last bit of code below) and tried to test but it gives me runtime errors.
Controller Bean
import java.sql.Blob;
@Entity
@Table(named = "files")
@NamedQueries( {
@NamedQuery(name = "MyBlob.getBlob",
query = from MyBlob WHERE fileId =: fileId")
})
public class MyBlob implements Serializable {
private Integer fileId;
private Blob file;
...
public Integer getFileId() {
return fileId;
}
public void setFileId() {
this.fileId = fileId;
}
public Blob getFile() {
return file;
}
public void setFile(Blob file) {
this.file = file;
}
....
}
BlobDao.java File method to get blob
public MyBlob getBlob(Integer fileId) throws HibernateException {
Session session = getSessionFactory().openSession();
try {
MyBlob blob = (MyBlob)session.getNamedQuery("MyBlob.getBlob").setInteger("fileId", fileId).uniqueResult();
return blob;
} catch(HibernateException e) {
throw new HibernateException(e);
} finally {
session.close();
}
}
TestDao.java
@Test
public void testBlob() {
MyBlob test = blobdao.getBlob(1); // 1 is a fileId that exists in the DB with a blob image file.
Blob blob = test.getFile();
try {
System.out.println(blob.length)); //this prints a number but I dont think the right one.
if(blob.length > 0 ) {
System.out.println(blob.toString() ); //errors out here
}
} catch(SQLException e) {
return System.out.println("Failed");
}
}
I am not sure that I am doing this right at all. Any help would be great. Thanks.