Google
 
Web unafbapune.blogspot.com

Tuesday, June 21, 2005

 

Oracle Blob mapped to byte[] in Hibernate

I refer to Oracle 9i and Hibernate 2.1 to 3.0.5.

As found in the Hibernate forum, there is a problem of mapping a byte[] JavaBean property to "binary" in the Hibernate mapping file. Basically the byte array can be written to Oracle, but what's read back from Oracle is always 86 bytes which is the Oracle Blob locator itself!

Here is one solution I've found to get around this problem, assuming, say, the byte[] property name is "image",
  1. Keep an internal member field for the byte[] image, with the standard {get|set}Image methods;
  2. Add a pair of {get|set}ImageBlob methods for getting and setting the Blob datatype, without the repsective Blob member field. This pair of methods are intended to be invoked only by Hibernate;
  3. Change the property mapping from "image" to "imageBlob", and use "blob" instead of "binary" for the type in the Hibernate mapping file.
Now the blob can be written to and read back from Oracle as byte[] as expected.

Note, with this approach, you may need to use the Oracle 10.1.0.4+ JDBC thin driver regardless to get around a problem related to the blob size greater than 2K bytes (even if you are running the Oracle 9.2.0.x database). Apparently it's related to a bug in the 9.2.0.x JDBC driver.

Example:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.SQLException;

import org.hibernate.Hibernate;

public class Foo implements Serializable {
byte[] image;

public byte[] getImage() {
return image;
}

public void setImage(byte[] image) {
this.image = image;
}

/** Don't invoke this. Used by Hibernate only. */
public void setImageBlob(Blob imageBlob) {
this.image = this.toByteArray(imageBlob);
}

/** Don't invoke this. Used by Hibernate only. */
public Blob getImageBlob() {
return Hibernate.createBlob(this.image);
}

private byte[] toByteArray(Blob fromBlob) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
return toByteArrayImpl(fromBlob, baos);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException ex) {
}
}
}
}

private byte[] toByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos)
throws SQLException, IOException {
byte[] buf = new byte[4000];
InputStream is = fromBlob.getBinaryStream();
try {
for (;;) {
int dataSize = is.read(buf);

if (dataSize == -1)
break;
baos.write(buf, 0, dataSize);
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
}
return baos.toByteArray();
}
}

Sample property mapping:
<property name="imageBlob" type="blob" column="IMAGE" />

Comments:
What about null byte array values? :>
 
You can check out the BlobUtils in beanlib
http://sourceforge.net/projects/beanlib
for the toByteArray() conversion. It takes care of null byte array, so you don't need to worry about it.
 
Were you able to cache blob fields in the second level cache using this method?

Thanks!
 
It seems Blobs are not cacheable. If you specify the cache-usage element in the Hibernate mapping file, you will get an exception:

Caused by: java.lang.UnsupportedOperationException: Blobs are not cacheable
at org.hibernate.type.BlobType.disassemble(BlobType.java:82)
...
 
Hello.

Just wanted to say that your posting was very helpfull for me, using DB2!

THANX
 
Hi!

It worked for me too, using MySQL!

Thank you!
 
I'm trying to use this method on DB2 and am cinsistently getting:


SQL0423N Locator variable "1" does not currently represent any value. SQLSTATE=0F001

at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)

One thing to note is that I am not using transactions.
 
It seems a previous comment from Ronald Pieterse has some success with DB2. Any idea from Ronald ?

Also, I suggest future posting should be made to the Sourceforge beanlib public forum at
http://sourceforge.net/forum/?group_id=140152
so that others can more easily share the information.
 
Hi, Your code was very helpfull but I still need your help in here. Database is Oracle 9.x plus we use Hibernate. I implement the blob code and the result was an insert followed by an update as a result that my transaction rollback since I only need to insert the data (new data). I add the timestamp in my xml file to avoid having an update that follows my insert.

Could you please help in here.

Many thanks
 
You can map two different classes to the same underlying entity. One with the blob property marked as immutable and one not. (The two classes can extend from the same base abstract class for ease of implementation.)
 
Thanks - this helped my in MySQL as well. Getting a "org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1" exception now, but it may be unrelated to the Blob...
 
Hello...

First of all, congrats. I'm trying to use your idea with Firebird, but I'm having problems. The fact is that I'm not inserting an image... I'm inserting a String. Have you tried it with a normal String?

Instead of inserting what I wrote, it inserts like "M" or "X" or letter that has nothing to do with the case.

Also, when I try to select my rows, I get the error: "Hibernate ExceptionException occurred inside setter of auge.bean.Cor.descricaoBlob".

Would you or someone else maybe know?

Sorry for bothering.

Letícia.
 
Admittedly I haven't tried Firebird. As to String or Image, it shouldn't matter. You can treat them all as image/binary. After all, it's just a stream of bytes underneath. I used this technique on XML strings all the time, and it's perfectly fine.
 
thank you! god bless you (by the deity of choice, or lack there of...)!
 
Looks like
public Blob getImageBlob() { return Hibernate.createBlob(this.image); }
is throwing PropertyAccessException for null bytes. BlobUtils method only takes care of setter and not getter() method.

I changed variable declaration to
private byte[] Image={};
from
private byte[] Image;
and works fine.
 
You shouldn't need to initialize image to {}, though, as the setter method is always invoked by Hibernate prior to the getter method being invoked by the application, and if BobUtils.toByteArray() is used in your setter method, the image field will always be set to a non-null array.
 
Hi

This code has used alot, but i want to store from jsp file using file filed. how to set to setBlob method.

And i want to read from the database. how to set blob to byte

Please send me the sample code

My mail id is : jm_reddy@rediffmail.com
Thank you
 
Make sure that you have hibernate.jdbc.use_streams_for_binary=true in hibernate.properties file (if you have the hibernate.jdbc.use_streams_for_binary in the hibernate.cfg.xml it will not be used). In the hibernate code, they are using hibernate.properies for 2 properties

1. hibernate.jdbc.use_streams_for_binary and
2. hibernate.cglib.use_reflection_optimizer

If you have the hibernate.jdbc.use_streams_for_binary=true in hibernate.properties file,

then

< property name="document" type="binary" column="SUPPORTING_DOC" / >

will work. You will not get the oracle blob reader.

Lakshmanan
 
Hello all,

My webapp is getting data from the business layer application using EJBs.

Persistence is made with Hibernate in the business layer. So getting the Blob locator in most cases is good form me.
e.g: List findFiles();

But sometimes, I need to get the entire data. like FileModel findFile(id);

I tried to let the hibernate property on file.getContent() and then I do
file.setBlobContent(Hibernate.createBlob(file.getContent()));

but this doesn't work. My content still returns 86 bytes.

How can I do lazy loading and still have access to my blob content in the web layer ?
 
Can you please post your questions to the beanlib forum at either https://sourceforge.net/forum/forum.php?forum_id=470285 or https://sourceforge.net/forum/forum.php?forum_id=470286 ?

I will try to answer them there.
 
Hi,

First of all, Thanks for the great great great sample.

After tweaking around the code just a little bit, I managed to get it work with Spring, Hibernate Xdoclet, MySql combination.
 
Thanks - it worked first try once I tried your strategy.
 
In my situation, I need to deal with LONG (Oracle 10g column type) instead of BLOB. I wonder what Hibernate type I should map to?
Thanks, Lieyong Fu (lfu@virginmobileusa.com)
 
Just FYI in case someone else has the same issue. Using type="text" resolved the 32K byte limitation problem that was caused by mapping a String variable to a LONG column in Oracle 10g. I believe that Hibernate does something like setCharacterStream when mapped to type="text" as opposed to setString when mapped to type="string".
 
I'm trying to get this to work with spring, hibernate, xdoclet and oracle. Can anyone tell me what the xdoclet mapping parameters would need to be
 
No need to copy the data yourself. Use:

blob.getBytes(1, (int) blob.length());
 
I am using this approach in my webapplication.It works fine with Struts Form File(getting the byte array i.e byte[] fileData = myFile.getFileData();
) when storing the image for the 1st time..but when editing i directly use the byte array which is in session if the user has not modified the file.

In this case while doing the update ,my server freezes and nothing happens...could someone please help.
 
Worked great. Thanks lot for sample code.
 
IT WORRRRKKKKKSSSSSSSSSS!!!!!!!!!!
 
I am new to Hibernate.
I am trying to use hibernate3.1 with MySql5.0.

I have a Java POJO class with a 'byte[] attriubte' and I need to write/read that to my Database.
Should I use this approach? or use the one described in here:
http://www.hibernate.org/73.html
 
How can you update Oracle 10.1.0.4+ JDBC thin driver ? I update it in my hibernate library class. I am not sure if I have to update it in the oracle directory. Please advice.
 
Just make sure the required Oracle jdbc thin driver is loaded first from your classpath. Whether it's in a specific directory depends on your classpath specification and classloader being used.
 
I cant able to implement your code.. when i use HQL.. its throwing an error stating ORA-00932: inconsistent datatypes: expected - got BLOB


i copeid the hibernate generated query and put that in sql plus and tried and I got the same error too,, does anyone has idea..
Kasi
 
Hi,

I also used your code it works fine for me to, using Hibernate + MySQL 5.0 with MySQL 4... there is no problem using Blob as MySQL saved it as String and one can get simply by using String but in MySQL 5... there is a problem, internally MySQL saved it as Binary Array. So if you have a field of type String then even you can use it, following is modified example instead of Image i will use a field Text

Example:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.SQLException;

import org.hibernate.Hibernate;

public class Foo implements Serializable {
byte[] Text;

public java.lang.String getText() {
return new String(text);
}

public void setText(java.lang.String text) {
this.text = text.getBytes();
}

/** Don't invoke this. Used by Hibernate only. */
public void setTextBlob(Blob TextBlob) {
this.Text = this.toByteArray(TextBlob);
}

/** Don't invoke this. Used by Hibernate only. */
public Blob getTextBlob() {
return Hibernate.createBlob(this.Text);
}

private byte[] toByteArray(Blob fromBlob) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
return toByteArrayImpl(fromBlob, baos);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException ex) {
}
}
}
}

private byte[] toByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos)
throws SQLException, IOException {
byte[] buf = new byte[4000];
InputStream is = fromBlob.getBinaryStream();
try {
for (;;) {
int dataSize = is.read(buf);

if (dataSize == -1)
break;
baos.write(buf, 0, dataSize);
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
}
return baos.toByteArray();
}
}

Sample property mapping: where TEXT is a blob field in MySQL Table...

property name="textBlob" type="blob" column="TEXT"

Muhammad Khurram Hanif
ProjectManager, Germany
 
Worked at first try! Thanks! I was looking for a solution for quite a long time...
 
you can replace the toByteArray() methods with :

byte[] b=
blob.getBytes(1, (int)blob.length())
 
Thank you for this code! To all users, PLEASE NOTE To avoid StaleObjectStateExceptions which you may get if two or more threads concurrently access this data, you should revise the Hibernate setter and getter methods so that it does not do any blob->byteArray conversions. Instead, from the example, change the "byte[] image" variable to be of type Blob (java.sql.Blob). Then modify the getImageBlob and setImageBlob to just return and set the Blob variable.
In the getImage and setImage methods, do the conversion to the byte array there.

Without doing this I was getting unnecessary updates occurring on this Hibernate object and this was causing the StaleObjectStateException.
 
I tried to apply the same logic above to store image file into MySQL database but for some reason, I get below exception(chain exception). Any help would be appreciated. Thanks!!

IllegalArgumentException in class: biz.mediabalance.domain.Picture, setter method of property: picture

xpected type: [B, actual value: org.hibernate.lob.SerializableBlob

Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:42)
... 91 more... 91 more
 
Can you please post the problem to the beanlib forum at sourceforge, and give more details there like which version of beanlib, hibernate, etc. you are using ?

http://sourceforge.net/forum/forum.php?forum_id=470286
 
Thanks a lot. It helped me a lot. I used the same code with MySQL and it works great. Have based your post in one of my posts too.
 
Hi,
your code works fine for me on postrgesql 8.2 and Oracle 10.
I still have the problem you describe at the begining of your web page, means I can not handle blob that are bigger than 2 Ko in Oracle 10.
I am using the latest jdbc thin driver (ojdbc14.jar) and can't use oci driver.
Can you tell me if you manage to handle big blobs ?

Regards,
__cyrille__
 
Hi,
I change the ojbdc14.jar, and it works fine. Thanks again for your code.
 
hi,
i am storing image in mysql database using hibernate.
My problam is ,it is storing in db.
when i store this on desktop and open it , it is empty only.
But the size showing some 70 kb.

can you tell me why the image doesnot display.
 
I just want to say THANK YOU!!! finally someone solve the BLOB issue in Hibernate. This post should be in the next version of Hibernate tutorial on "How to save a file".
 
I use the BlobByteArrayType that provide Spring for the Blob handing and it work fine, but i'm facing with problems using with beanlib so, somebody have been tried this?..
Some Help will be nice ..
 
Please read the messages at the beanlib help forum. Basically you need to plug in your own CustomTransformSpi to handle the BlobByteArrayType.
 
everyone,

I've developed the Web application, and one of its functions is to upload PDF file to database as BLOB type. However, when I try to update BLOB column using Hibernate, Spring and Oracle, the update works sometimes, and other times it doesn't. Is it a known issue of Hibernate and Oracle? I'm using JDBC 10.0.4 driver and Hibernate 3. I've been looking for a workaround solution for days and didn't find any thing helpful yet. I didn't get any error even when the BLOB didn't get updated as supposed. Here is the snip of my codes:

final Blob blob = Hibernate.createBlob(jobDescription.getJobDescription());
log.debug("Successfully created blob object");
log.debug("and here is the content of the BLOB");
System.out.println(blob);

practitionerDTO.setJobDescription(blob);
practitionerDTO.setJobDescriptionAvailabe(true);
practitionerDTO.setLastUpdateDate(new Date());

// updating the practitioner record with the job description and last
// updated date
getPractitionerServices().updatePractitioner(practitionerDTO);
--------------------------------
here, it's the snip of my hibernate mapping.
property name=jobDescription type="blob"
column name=JOB_DESC
-----------

if you can, please contact me through e-mail, vnguyen_1999@yahoo.com with suggestions or solution. I appreciate your time and effort.
 
Thanks all.

I am using MS SQL server.

my property specification is
property name="fileContent" type="java.sql.Blob"
column name="file_content"
property

file_content is of type IMAGE in DB.

data is saving properly.
But when I retrieve and read using the statement


InputStream in=new BufferedInputStream(content.getBinaryStream());

I am getting this exception


com.jnetdirect.jsql.m: Invalid position index:0
at com.jnetdirect.jsql.n.getBytes(JI)[B(Unknown Source)
at com.jnetdirect.jsql.n.getBinaryStream()Ljava.io.InputStream;(Unknown Source)
at org.hibernate.lob.SerializableBlob.getBinaryStream(SerializableBlob.java:39)
at stanford.gsb.cps.view.bean.admin.FileUploadAdminBean.getFilePaths(FileUploadAdminBean.java:117)
at stanford.gsb.cps.view.bean.admin.FileUploadAdminBean.setInitialized(FileUploadAdminBean.java:63)
at jrockit.reflect.VirtualNativeMethodInvoker.invoke(Ljava.lang.Object;[Ljava.lang.Object;)Ljava.lang.Object;(Unknown Source)
at java.lang.reflect.Method.invoke(Ljava.lang.Object;[Ljava.lang.Object;I)Ljava.lang.Object;(Unknown Source)
at org.apache.myfaces.el.PropertyResolverImpl.setProperty(PropertyResolverImpl.java:368)
at org.apache.myfaces.el.PropertyResolverImpl.setValue(PropertyResolverImpl.java:148)
at org.apache.myfaces.config.ManagedBeanBuilder.initializeProperties(ManagedBeanBuilder.java:176)
at org.apache.myfaces.config.ManagedBeanBuilder.buildManagedBean(ManagedBeanBuilder.java:55)
at org.apache.myfaces.el.VariableResolverImpl.resolveVariable(VariableResolverImpl.java:311)
at org.springframework.web.jsf.DelegatingVariableResolver.resolveVariable(DelegatingVariableResolver.java:108)
at com.sun.facelets.el.LegacyELContext$LegacyELResolver.getValue(LegacyELContext.java:134)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:65)
at com.sun.el.parser.AstValue.getValue(AstValue.java:106)
at com.sun.el.parser.AstNot.getValue(AstNot.java:46)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:192)
at com.sun.facelets.el.TagValueExpression.getValue(TagValueExpression.java:71)
at com.sun.facelets.el.LegacyValueBinding.getValue(LegacyValueBinding.java:56)
at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:307)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:864)
at javax.faces.component.UIForm.processDecodes(UIForm.java:144)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:872)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:306)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:79)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:90)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)

Please help.
 
Hi All,

If you use Spring + Hibernate this problem can be solved with UserType provided from Spring:

Into spring config file
1. bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"

2. bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
property name="lobHandler" ref="lobHandler" ...

Into mapping
3.
property name="picture" type="org.springframework.orm.hibernate3.support.BlobByteArrayType"

where picture will be byte[] type.
 
Please send me an example of saving image into Mysql using struts and hibernate.
Satyendra Saini
 
this is very good blog for new users.
 
I am doing same as you explained but my cpu usage reaches100% while storing images and it is not able recover for a long time. waht could be the reason?

--Kiran R
 
How large is your image(s) ? Could it be related to memory shortage leading to too much GC activities ? I would turn on the vergosegc, etc. to see what's happening. HTH.
 
Hi, i'm also having a problem in retrieving blob from oracle 10g (express edition) in hibernate. I'm using the latest drivers both for ojdbc and hibernate.

My problem is also the 86bytes being retrieved by hibernate. I cannot implemnt hanson char's code because i'm implementing this as a web service in sun app server. I'm getting a compilation error when including importing the java.sql library.

I have tried using the oci driver, it works but when the blob length is greater than 4000, i cannot retreive the rest byte value (> 4000 bytes).
 
I get an exception, when the image in the DataBase is null. What should i change from the code, to solve this problem. I'm a newbie programmer. Thanks a lot.
Monica

Exception:
net.sf.hibernate.PropertyAccessException: Exception occurred inside setter of it.cabotomarkethub.persistence.entity.Ut
ente.imageBlob
net.sf.hibernate.PropertyAccessException: Exception occurred inside setter of it.cabotomarkethub.persistence.entity.Utente.imageBlob
at net.sf.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:49)
Caused by: java.lang.reflect.InvocationTargetException
Caused by: java.lang.NullPointerException
at it.cabotomarkethub.persistence.entity.Utente.toByteArrayImpl(Utente.java:254)
 
Hi the hibernate mapping entry saved our day, thx very much!
 
I am using MySQL, but when I am trying to convert that blob in byte[] while reading from database. It's showing me this error.

org.hibernate.MappingException: No Dialect mapping for JDBC type: -4

Any idea, what could we do to remove this error.
 
Check your hibernate-config.xml file for Dialect mapping.If you do not define it,define it first then problem will be short out.
 
I had the same problem where I could write a byte[] to an Oracle DB BLOB column fine but would give me garbage coming back out.

Turns out my ORACLE_HOME environment variable wasn't set to /blah/10.x.x.x/client my LD_LIBRARY_PATH not set to include $ORACLE_HOME/lib and my $CLASSPATH not set to include $ORACLE_HOME/jdbc/lib/ojdbc14.jar & $ORACLE_HOME/jdbc/lib/classes12.jar

That's it. It was kind of annoying, I wasn't getting an kind of an error, I just got some junk Oracle header put into the first 36 bytes of the array. I haven't had a chance to dig into the Hibernate code, but I guess it tries loading the byte stream into one of those Blob named classes in the jars like BlobAccessor or OracleBlobInputStream which will do a little magic (like the 'file' command does) and strip out the header before populating the byte[]. And if none of those classes recognize it all the junk goes into the byte[].
 
stupid mistake i made ... was using classes12.jar instead of ojdbc14.jar ...
 
I encountered the same issue using Oracle 9.x. The solution provided here did resolve the problem, and I went with the 11g driver. This may have been a mistake because the solution has introduced an issue that was not present in Oracle 9.x. I am experiencing somewhat intermittent commit hang conditions that seem to be associated with update operations. Tracing Hibernate reveals the execution is hanging on a "DEBUG LongType:133 - binding '14' to parameter: 12" operation.

My question is, what does the table schema look like. Do you have a column for image and image_blob?
 
Also, what were the annotations for the two 'image' columns? If "@Column" equivalents can be provided, it would be appreciated.
 
Hi, Your solution is very good. Im using Java, Hibernate and Oracle 10G.

I am trying to store a PDF as a blob in the database.

So, Im able to store it, and also retrieve it in my web application online...

Then I have a java batch job that needs to retrieve all these pdfs from the database and then zip them and send them to another server.

So in the batch job, when I invoke the same dao to fetch the pdfs (as a blob), I get Connection closed exception....CAn u help?
 
I encounted the same issue, and used the code above, but it seems it did work, it will produce a null in the column in db; so I made some modification;I have a field Map<String, Object> to save in db; my environment is jdk1.6, oracle 10:

public class Subscription implements Serializable, ISubscription {
private Map<String, Object> parameters;
public Map<String, Object> getParameters() {
return parameters;
}
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
/**
* don't call it, its is for hibernate
*/
@XmlTransient
public byte[] getParameterBlob() throws IOException {
// return parameterBlob;
// create a Blob
if(parameters == null){
return null;
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(parameters);
oo.flush();
bo.flush();
byte[] bytes = bo.toByteArray();
bo.close();
oo.close();
return bytes;
}
/**
* don't call it, its is for hibernate
*/
public void setParameterBlob(byte[] fromBlob) throws SQLException,
IOException, ClassNotFoundException {
if(fromBlob == null|| fromBlob.length==0){
setParameters(null);
return;
}
byte[] buf = new byte[4000];
InputStream is = new ByteArrayInputStream(fromBlob);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
for (;;) {
int dataSize = is.read(buf);
if (dataSize == -1)
break;
baos.write(buf, 0, dataSize);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
ByteArrayInputStream bi = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
Map<String, Object> map = (Map<String, Object>) oi.readObject();
setParameters(map);
oi.close();
bi.close();
}
}
 
the property in hbm is as following:
<property name="parameterBlob" column="parameterblob" type="binary"></property>
 
vary good
 
Also wanted to say that your tip saved the day for me. Many thanks :)
 
more then 5 years after your original post....
thanks,thanks and again thanks!!
Helpfull, clear and perfectly working!
 
Hi all. I've found a simplier solution that worked for me in JPA:
just decorate your field with @Type annotation:
@Type(type = "org.hibernate.type.PrimitiveByteArrayBlobType")


Example:
@Lob
@Column(name = "F_BLOCKINFO", length = 0)
@Type(type = "org.hibernate.type.PrimitiveByteArrayBlobType")
private byte[] _blobdata;
 
Mine is thick client application and I sending my image as a byte[]. I modified my code as you said but I gets this exception

"org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of erp.domain.School.logo"

I am setting the image attribute in setAttribute() methode like
logo = new SerialBlob((byte[]data));

before passing to session.save(school);

Its working fine and get image gets saved along with other fields.

Please help me.Any help will be appreciated thank you in advance
 
Seems similar to this: http://forum.springsource.org/archive/index.php/t-23090.html
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?