I am having trouble getting blob data from my database using java in a JSF 2.0 application. The first problem I came across is my getter method for Blob named "file". I get the error "Basic attributes can only be of the following types ...", basically saying that I cannot return a Blob object. My code looks like below. Even with an error, my code compiles. I created a test method (last bit of code below) and tried to check, but it gives me runtime errors.
Bean controller
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 for getting 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);
Blob blob = test.getFile();
try {
System.out.println(blob.length));
if(blob.length > 0 ) {
System.out.println(blob.toString() );
}
} catch(SQLException e) {
return System.out.println("Failed");
}
}
I'm not sure I'm doing it right. Any help would be great. Thank.