How to handle blob data with java and mysql and hibernate

Dear all,
I am using java 1.6 and mysql 5.5 and hibernate 3.0 . Some time i use blob data type . Earlier my project's data base was oracle 10g but now i am converting it to Mysql and now i am facing problem to save and fetch blob data to mysql database . Can anybody give me the source code for blob handling with java+Mysql+Hibernate
now my code is :--
==================================================
*.hbm.xml :--
<property name="image" column="IMAGE" type="com.shrisure.server.usertype.BinaryBlobType" insert="true" update="true" lazy="false"/>
===================================================
*.java :--
package com.shrisure.server.usertype;
import java.io.OutputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import oracle.sql.BLOB;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import org.jboss.resource.adapter.jdbc.WrappedConnection;
import com.google.gwt.user.client.rpc.IsSerializable;
public class BinaryBlobType implements UserType, java.io.Serializable, IsSerializable {
private static final long serialVersionUID = 1111222233331231L;
public int[] sqlTypes() {
return new int[] { Types.BLOB };
public Class returnedClass() {
return byte[].class;
public boolean equals(Object x, Object y) {
return (x == y) || (x != null && y != null && java.util.Arrays.equals((byte[]) x, (byte[]) y));
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
BLOB tempBlob = null;
WrappedConnection wc = null;
try {
if (value != null) {
Connection oracleConnection = st.getConnection();
if (oracleConnection instanceof oracle.jdbc.driver.OracleConnection) {
tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
if (oracleConnection instanceof org.jboss.resource.adapter.jdbc.WrappedConnection) {
InitialContext ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("java:/DefaultDS");
Connection dsConn = dataSource.getConnection();
wc = (WrappedConnection) dsConn;
// with getUnderlying connection method , cast it to Oracle
// Connection
oracleConnection = wc.getUnderlyingConnection();
tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
tempBlob.open(BLOB.MODE_READWRITE);
OutputStream tempBlobWriter = tempBlob.getBinaryOutputStream();// setBinaryStream(1);
tempBlobWriter.write((byte[]) value);
tempBlobWriter.flush();
tempBlobWriter.close();
tempBlob.close();
st.setBlob(index, tempBlob);
} else {
st.setBlob(index, BLOB.empty_lob());
} catch (Exception exp) {
if (tempBlob != null) {
tempBlob.freeTemporary();
exp.printStackTrace();
st.setBlob(index, BLOB.empty_lob());
// throw new RuntimeException();
} finally {
if (wc != null) {
wc.close();
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
final Blob blob = rs.getBlob(names[0]);
return blob != null ? blob.getBytes(1, (int) blob.length()) : null;
public Object deepCopy(Object value) {
if (value == null)
return null;
byte[] bytes = (byte[]) value;
byte[] result = new byte[bytes.length];
System.arraycopy(bytes, 0, result, 0, bytes.length);
return result;
public boolean isMutable() {
return true;
public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
return assemble(arg0, arg1);
public Serializable disassemble(Object arg0) throws HibernateException {
return disassemble(arg0);
public int hashCode(Object arg0) throws HibernateException {
return hashCode();
public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
return replace(arg0, arg1, arg2);
=================================================================
can anyone give me the source code for this BinaryBlobType.java according to mysql blob handling ..

Moderator action: crosspost deleted.

Similar Messages

  • How to bulk import data into CQ5 from MySQL and file system

    Is there an easy way to bulk import data into CQ5 from MySQL and file system?  Some of the files are ~50MB each (instrument files).  There are a total of ~1,500 records spread over about 5 tables.
    Thanks

    What problem are you having writing it to a file?
    You can't use FORALL to write the data out to a file, you can only loop through the entries in the collection 1 by 1 and write them out to the file like that.
    FORALL can only be used for SQL statements.

  • How to handle same product with different part numbers and pricing in SAP.

    I am a new user and want to learn if the following scenario can be handled by SAP.
    Our business buys a product from a supplier which has 2 different part numbers and prices. It is the same product. One is the primary product whilst the other is available only as an upgrade option with a different part number to a mainline product at a cheaper price .
    Our issue is that we sometimes buy the upgrade option with a mainline product to get the better price even though these go into stock. Basically we need to have the items linked with both part numbers in SAP at different prices but inventory both in and out only going against the primary part number. Any ideas?

    Thanks Jitin
    I did give them different part numbers and then attached a Bom containing the primary part number against the upgrade option however I really need to have the secondary item as a sales and purchase item but non inventory so the stock comes from the primary part. Ideally  if we receipt the goods in as the secondary number the inventory goes to the primary part. If the second number is an inventory item then I have the issue of the same part with different part numbers sitting in stock at different prices and having to rely on employees understanding the difference.
    Sorry to be so confusing. I will do some more testing over the weekend and see if I can find a suitable solution.
    Thanks
    Martin

  • How to display data with the same text and key in the drop down list?

    Hi All,
    Would like so to seek for you advice on the above mention topic. How to display the data with the same text and key using function module 'VRM_SET_VALUES'. From my testing by writing a program, this function module will only show the text and key if both have different data. Please find the coding as below. Is the normal behaviour of this function module? How to overcome this problem? Thanks in advance.
    REPORT ZTESTING.
    TYPE-POOLS: VRM.
    DATA: NAME  TYPE VRM_ID,
          LIST  TYPE VRM_VALUES,
          VALUE LIKE LINE OF LIST,
          c(20) type c.
    *      c = 'select any'.
    data:begin of itab occurs 0,
          kunnr like kna1-kunnr,
          name1 like kna1-name1,
         end of itab.
    data:begin of jtab occurs 0,
          kunnr like kna1-kunnr,
          land1 like kna1-land1,
         end of jtab.
    PARAMETERS: p_list(20) AS LISTBOX VISIBLE LENGTH 20
                              default 'SELECT'.
    AT SELECTION-SCREEN OUTPUT.
    NAME = 'p_list'.
    VALUE-KEY = 'Name'.     "---> Data for key is the same with text
    VALUE-TEXT = 'Name'.    "--> Data for text is the same with key
    APPEND VALUE TO LIST.
    VALUE-KEY = '2'.
    VALUE-TEXT = 'Country'.
    APPEND VALUE TO LIST.
    CALL FUNCTION 'VRM_SET_VALUES' EXPORTING ID = NAME VALUES = LIST.
    start-of-selection.
    select kunnr name1 up to 20 rows from kna1 into table itab.
    select kunnr land1 up to 20 rows from kna1 into table jtab.
    case p_list.
    when '1'.
    loop at itab.
    write:/ itab-kunnr,itab-name1.
    endloop.
    when '2'.
    loop at jtab.
    write:/ jtab-kunnr,jtab-land1.
    endloop.
    endcase.
    <Added code tags>
    Moderator Message: Please use the "code" tags to format your code snippet.
    Edited by: Suhas Saha on Nov 17, 2011 11:19 AM

    shawnTan wrote:
    Hi All,
    >
    > Would like so to seek for you advice on the above mention topic. How to display the data with the same text and key using function module 'VRM_SET_VALUES'. From my testing by writing a program, this function module will only show the text and key if both have different data. Please find the coding as below. Is the normal behaviour of this function module? How to overcome this problem? Thanks in advance.
    >
    >
    REPORT ZTESTING.
    >
    > TYPE-POOLS: VRM.
    >
    > DATA: NAME  TYPE VRM_ID,
    >       LIST  TYPE VRM_VALUES,
    >       VALUE LIKE LINE OF LIST,
    >       c(20) type c.
    >
    > *      c = 'select any'.
    >
    > data:begin of itab occurs 0,
    >       kunnr like kna1-kunnr,
    >       name1 like kna1-name1,
    >      end of itab.
    >
    > data:begin of jtab occurs 0,
    >       kunnr like kna1-kunnr,
    >       land1 like kna1-land1,
    >      end of jtab.
    >
    > PARAMETERS: p_list(20) AS LISTBOX VISIBLE LENGTH 20
    >                           default 'SELECT'.
    >
    > AT SELECTION-SCREEN OUTPUT.
    >
    > NAME = 'p_list'.
    >
    > VALUE-KEY = 'Name'.     "---> Data for key is the same with text
    > VALUE-TEXT = 'Name'.    "--> Data for text is the same with key
    > APPEND VALUE TO LIST.
    >
    > VALUE-KEY = '2'.
    > VALUE-TEXT = 'Country'.
    > APPEND VALUE TO LIST.
    >
    > CALL FUNCTION 'VRM_SET_VALUES' EXPORTING ID = NAME VALUES = LIST.
    >
    > start-of-selection.
    > select kunnr name1 up to 20 rows from kna1 into table itab.
    > select kunnr land1 up to 20 rows from kna1 into table jtab.
    >
    > case p_list.
    > when '1'.
    > loop at itab.
    > write:/ itab-kunnr,itab-name1.
    > endloop.
    >
    > when '2'.
    > loop at jtab.
    > write:/ jtab-kunnr,jtab-land1.
    > endloop.
    > endcase.
    >
    > <Added code tags>
    >
    > Moderator Message: Please use the "code" tags to format your code snippet.
    >
    > Edited by: Suhas Saha on Nov 17, 2011 11:19 AM
    This surely seems to be a bug to me(if not by design),  did you check for any SAP notes? Perhaps a front end trace can help(Note 407743) !
    -Rajesh.

  • How I average data with 78,74,73 and 55 points respectively and end up with an array of 78 points for the average?

    Hi
    As the questions states, how do I average data with 78,74,73 and 55 points respectively and obtain an array of 78 points? 
    When I use the plus vi, Labview somehow produces an array of 55 points when I do the average (see attached vi).
    I have been unlucky in trying to get good results.
    Can anyone help?
    Thank you.
    Attachments:
    average4.vi ‏40 KB

    The add function is polymorphic. It accepts arrays as well as numerics, but you need to understand one thing about array operations in LV. Operations performed on arrays of different sizes will always (I think) work based on the smallest array. For example, if you auto index 2 arrays of different sizes into a for loop, the number of times the loop will run will be the size of the small array. The same is true here - when you wire 2 arrays of different sizes to the add function, only the first N elements of the larger array get processed. The rest are dumped. That's why you get 55 elements.
    Attached is a modification of your VI which shows 2 things:
    The bottom part is your algorithm, only cleaned up. Note how much easier it would be to read now. You should always write clean code. Also, note that I have changed the representation on some of the data from DBL to I32. This is because this is the representation the array function work with and your code had the DBLs coerced for no reason.
    The top part is a different algorithm which should do what you want. Note that like Mike said, the arrays with smaller sizes will have 0s appended at the end, so if you want to avoid that, you will have to modify the last part, where the averaging is done and only divide those columns which are long enough.
    To learn more about LabVIEW, I suggest you try searching this site and google for LabVIEW tutorials. Here and here are a couple you can start with. You can also contact your local NI office and join one of their courses.
    In addition, I suggest you read the LabVIEW style guide and the LabVIEW user manual (Help>>Search the LabVIEW Bookshelf).
    Try to take over the world!
    Attachments:
    average4MOD.vi ‏63 KB

  • In  BDC how you handled header data and item data

    In  BDC how you handled header data and item data

    Raja,
    Can you be more clear ?
    Usually you load the header data one and then loop at the item data and then load the item data.
    This example should help you.
    http://www.sap-img.com/abap/bdc-example-using-table-control-in-bdc.htm
    Regards,
    Ravi
    Note - Please mark all the helpful answers

  • My iPhone is having problems and I have to send it into Apple to get a fixed but in the mean while I need a phone. Could my old env touch act as a temporary replacement with the data plan? And if so how to I activate it with going to Verizon and once I ge

    My iPhone is having problems and I have to send it into Apple to get a fixed but in the mean while I need a phone. Could my old env touch act as a temporary replacement with the data plan? And if so how to I activate it with going to Verizon and once I get my IPhone back will I be able to activate it without going to the Verizon store?!? Thanks:)

    Im sorry. Im on my ipad and i didnt read that.
    Sorry again

  • How to handle "xsd:anyAttributes" with jaxb

    Need help for how to handling "xsd:anyAttribute" with jaxb!
    Here is part of my xml schema.
    <xsd:attributeGroup name="DataAttributes">
    <xsd:anyAttribute namespace="##local" processContents="lax"/>
    </xsd:attributeGroup>
    <xsd:element name="Data">
    <xsd:complexType>
         <xsd:attributeGroup ref="DataAttributes"/>
    </xsd:complexType>
    </xsd:element>
    <xsd:element name="MA_Verify">
    <xsd:complexType>
         <xsd:sequence>
         <xsd:element ref="Data" minOccurs="0" maxOccurs="unbounded"/>
         </xsd:sequence>
         <xsd:attributeGroup ref="verifyAttributes"/>
    </xsd:complexType>
    </xsd:element>
    I have an application which only knows the attribute names and values at runtime. (Thest attributes are string.) Therefore, I cannot define attribute names in the schema and have to use xsd:anyAttribute.
    I was able to generate all jaxb code. However, the interfaces generated for Data and DataType are basically all empty. The impl classes are empty too, since no get or set methods exist for the attribute.
    Some thoughts for handling this case, but do not know if it will work.
    (1) write some derive classes on top of the generated jaxb classes.
    (2) write customized method to handle the 'Data' element level and its attributes. Similar to parseMethod or printMethod for the javaType.
    (if there is a way)
    Can anyone give me suggestions, directions or an laternate way to handle the situation?
    Your help will be greatly appreciated.
    Ruth

    xsd:anyAttribute is not supported by JAXB.
    http://java.sun.com/xml/jaxb/users-guide/jaxb-works.html#unsupported

  • Doubt handling Clob columns with Java JDBC api

    Hi,
    we have a doubt handling Clob columns with Java JDBC api.
    Reading Oracle 10g official documentation (document b10979.pdf, page 236), we found this note:
    ============================================
    To write LOB data, the application must acquire a write lock on the LOB object. One way to accomplish this is through a SELECT FOR UPDATE. Also, disable auto-commit mode.
    ============================================
    We also found a java sample code about how to handle Lob objects at this URL:
    http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/files/advanced/LOBSample/LOBSample.java.html
    In our java2 application, we access Clob objects in a quite different
    manner: we use normal setString() and getString() methods, as described into paragraph "Shortcuts For Inserting and Retrieving CLOB Data"
    (document b10979.pdf, page 244).
    Using those methods, we never lock the table row by a SELECT FOR UPDATE statement (as described into the note above). We use simply SELECT, UPDATE and INSERT prepared statement.
    In this way we can insert both clob objects and normal timestamp, number and other types with a single insert statement. Idem for update.
    To recap, our question is:
    Is it mandatory to create a SELECT FOR UPDATE statement when updating clob data? What may be the consequences if we don't use it? It is also correct to insert with a single sql statement both clob and not clob data using the setString() method for the clob types? And more than one lob column in the same record?
    bye,
    luca acri.

    And columns of type FLOAT. These also have, for some unknown reason a metadata type of OTHER, and a type string of 'FLOAT'. Yet PreparedStatement.setNull(x, Types.OTHER) doesn't work and setNull(x, Types.DECIMAL) does.

  • How to handle time&date

    can anyone tell me how to handle time&date correctly?using Calendar,GregorianCalendar,TimeZone,Locale
    thank you very much

    This is too large a topic to discuss in depth here. Here is a link to a tutorial on times and dates, and a search link that references many documents on the subject.
    http://java.sun.com/docs/books/tutorial/i18n/format/dateintro.html
    http://onesearch.sun.com/search/developers/index.jsp?and=calendar+&nh=100&phr=how+to&qt=&not=&field=&since=&col=javatecharticles&col=javatutorials&col=devall&rf=0&Search.x=20&Search.y=7
    When you have specific questions, just ask.

  • Problem with java swing button and loop

    Problem with java swing button and loop
    I�m using VAJ 4.0. and I�m doing normal GUI application. I have next problem.
    I have in the same class two jswing buttons named start (ivjGStart) and stop (ivjGStop) and private static int field named Status where initial value is 0. This buttons should work something like this:
    When I click on start button it must do next:
    Start button must set disenabled and Stop button must set enabled and selected. Field status is set to 1, because this is a condition in next procedure in some loop. And then procedure named IzvajajNeprekinjeno() is invoked.
    And when I click on stop button it must do next:
    Start button must set enabled and selected and Stop button must set disenabled.
    Field status is set to 0.
    This works everything fine without loop �do .. while� inside the procedure IzvajajNeprekinjeno(). But when used this loop the start button all the time stay (like) pressed. And this means that a can�t stop my loop.
    There is java code, so you can get better picture:
    /** start button */
    public void gStart_ActionEvents() {
    try {
    ivjGStart.setEnabled(false);
    ivjGStop.setEnabled(true);
    ivjGStop.setSelected(true);
    getJTextPane1().setText("Program is running ...");
    Status = 1;
    } catch (Exception e) {}
    /** stop button */
    public void gStop_ActionEvents() {
    try {
    ivjGStart.setEnabled(true);
    ivjGStart.setSelected(true);
    ivjGStop.setEnabled(false);
    getJTextPane1().setText("Program is NOT running ...");
    Status = 0;
    } catch (Exception e) {
    /** procedure IzvajajNeprekinjeno() */
    public void IzvajajNeprekinjeno() {  //RunLoop
    try {
    int zamik = 2000; //delay
    do {
    Thread.sleep(zamik);
    PreberiDat(); //procedure
    } while (Status == 1);
    } catch (Exception e) {
    So, I'm asking what I have to do, that start button will not all the time stay pressed? Or some other aspect of solving this problem.
    Any help will be appreciated.
    Best regards,
    Tomi

    This is a multi thread problem. When you start the gui, it is running in one thread. Lets call that GUI_Thread so we know what we are talking about.
    Since java is task-based this will happen if you do like this:
    1. Button "Start" is pressed. Thread running: GUI_Thread
    2. Event gStart_ActionEvents() called. Thread running: GUI_Thread
    3. Method IzvajajNeprekinjeno() called. Thread running: GUI_Thread
    4. Sleep in method IzvajajNeprekinjeno() on thread GUI_Thread
    5. Call PreberiDat(). Thread running: GUI_Thread
    6. Check status. If == 1, go tho 4. Thread running: GUI_Thread.
    Since the method IzvajajNeprekinjeno() (what does that mean?) and the GUI is running in the same thread and the event that the Start button has thrown isn't done yet, the program will go on in the IzvajajNeprekinjeno() method forever and never let you press the Stop-button.
    What you have to do is do put either the GUI in a thread of its own or start a new thread that will do the task of the IzvajajNeprekinjeno() method.
    http://java.sun.com/docs/books/tutorial/uiswing/index.html
    This tutorial explains how to build a multi threaded gui.
    /Lime

  • How to Get Blob data(In String Form) using OCCI

    Hello frnds,
    I am new to OCCI,so i hvnt that much of master in that side.
    I have one problem while handling BLOb data.
    How to convert binary form of SDO_GEOMETRY data into string format. I am able to convert data by using PLSQL block,but its take so much time to execute.So performance is the main issue.So if there is any API in OCCI which convert directly blob data into string format.
    Thanx in advance for your support,
    Nilesh.

    Have you tried reading "http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28390/lobs.htm#BABDEGJD" ? This explains how you can read from BLOBs into a C vector (or C++ vector of chars).

  • How do i mail merge with the new Pages and Numbers?

    How do I mail merge with the new Pages and Numbers?
    On Pages 09 I have a document that draws variable data from a spreadsheet created in Numbers.
    With the new Pages and Numbers program update, my links are lost and I am unable to see how to correct this.

    Thanks Peter,
    very disappointing.
    My Pages 09 keeps opening in the new one.
    I dont think they want me to be a loyal customer anymore.
    They changed Final Cut Pro, so now I use Premier Pro
    Aperture 3 has been left behind so now I moved to Lightroom 4.
    And now Pages 5 does not have a vital component, so back to Word.
    Sad day
    Thanks again

  • How to connect oracle database with JAVA

    how to connect oracle database with JAVA....
    using j2sdk and Jcreator . which connector to use .. what are the code for that ..

    PLEASE .... Ask in an Oracle Java forum.
    And read the documentaiton. There is a whole document devoted to doing that. http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/toc.htm has examples.
    PLEASE ... do not ask product questions in a forum which clearly has a title saying it is devoted to assisting with download problems.

  • How to view blob data.

    I had created a table for storing image as well as the package. How to view the image. I am using sql developer.. is it possible to view.. ?? or else how..??
    Is it possible to view through http connecting via oracle client to the database.

    You can save the BLOB column with help of UTL_FILE and UTL_RAW as operating system file and then view that with some external software.

Maybe you are looking for

  • EPS placed in InDesign CC, clicking "Edit with Illustrator CS6" will launch application but not open document.

    Happens irregularly, if you can call "several times a day" irregularly. Solved by quitting Illustrator and restarting. Coworkers report seeing the same issue.

  • VideoPlayer problems in Flash Builder 4.5

    Wanted to check and see if anyone else is having problems with videoplayer in 4.5. I insert the player, choose the flv file but it does not play once I run the application. I opened FlashBuilder 4 and built the page the same way and it plays fine. Ho

  • Currency change 'as requested'... without my knowl...

    Hi, I just received an email, and a message on my skype saying that my currency had been changed from £GBP to Euro 'as requested' However I do not use any of the paid features of skype, and I certainly did not request any changes to my account. I kno

  • WPA2 shows as WPA

    I have set up my airport extreme (firmware 7.2.1) for WPA2 Personel. I did the same in network preferences on my macbook. But the strange thing is that network preferences will always show it as WPA Personel. I have no trouble connecting and suspect

  • Imac has restarted with default settings?

    i  was  downloading flash player update  and did ,  then was asked to  restart firefox  which i did  then  the desktop  lost  all  icons  and  screen  looked like it did  when i  took it  out of the box  2 years ago,   all  music  is lost and recent