2

We are using hibernate mapping. In hibernate configuration file we have given type="blob" and pojo class getBlob and setBlob methods we have. Apart from this we need to have @lob right. what is equivalent for lob in hibernate mapping

@Override
public Hospital  getHospital(long hospId, String hospitalName) {
    Hospital hos= hibernateTemplate.find("from Hospital
    hos where hos.id = ? and hos.name = ? ", hospId,hospitalName);          
}
@Transactional
public void saveHospital(Hosipital hos) {
    Blob blob = Hibernate.getLobCreator(hibernateTemplate.getSessionFactory().getCurrentSession()).createBlob(hos.getContent());
    hos.setHospitalImage(blob);
    hibernateTemplate.saveOrUpdate("Hospital", hos);
}
Ravi
  • 159
  • 3
  • 17

3 Answers3

2

In my model I'm using the following:

@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "CONTENUTO_BLOB", nullable = true)
public Blob getContenutoBlob()
{
    return contenutoBlob;
}

The annotation @Lob indicates that it's a Lob column; the @Basic(fetch=FetchType.LAZY) indicates to load the entity without loading the Lob in memory; you can access to the lob only when you really need

UPDATE

Long time I don't use XML but if I'm not wrong you may use something like this:

 <property name="contenutoBlob" type="org.hibernate.type.BinaryType" lazy="true">
 </property>

UPDATE 2

I never used hibernateTemplate in any case also by using hibernateTemplate you can access to the hibernate session Usually I do the following:

Save Blob method

public void saveAllegato(InputStream fileIn, long lunghezza) throws DbException
    {
        //Dai test effettuati, quando siamo col portale attivo bisogna non chiudere
        //mai lo stream
        boolean closeStream = false;
        try
        {
            //sf is the SessionFactory
            Session sessione = sf.getCurrentSession();
            Blob blob = null;
            if (null != fileIn)
            {
                blob = Hibernate.getLobCreator(sessione).createBlob(fileIn, lunghezza);
            }
            AllegatoModel entity = new AllegatoModel();
            //Set the other fields
            if( blob != null )
            {

                entity.setContenutoBlob(blob);
            }
            // Save object
            sessione.saveOrUpdate(entity);
        }
        catch (Exception e)
        {
            String message = "Errore nel salvataggio della entity " + entity + "; " + e.getMessage();
            logger.error(message, e);
            throw new PinfGpDbException(message);
        }
        finally
        {
            if (fileIn != null)
            {
                try
                {
                    fileIn.close();
                }
                catch (Exception e)
                {
                    //Stampo lo stacktrace solo quando il log ha livello di debug
                    if( logger.isDebugEnabled() )
                    {

                        logger.debug("Errore nella chiusura del file input stream ", e);
                    }
                    else if( logger.isWarnEnabled() )
                    {
                        logger.debug("Errore nella chiusura del file input stream; "+e.getMessage());
                    }
                }
            }
        }

GET BLOB METHOD

public void writeAllegatoFile(Long id, OutputStream out) throws PinfGpDbException
{
    StopWatch sw = new StopWatch("SCRITTURA FILE CON ID ["+id+"] SU OUTPUTSTREAM");
    InputStream is = null;
    try
    {
        sw.start("RECUPERO FILE DA DB");
        DetachedCriteria criteria = DetachedCriteria.forClass(AllegatoModel.class);
        criteria.add(Property.forName("id").eq(id));
        ProjectionList pl = Projections.projectionList();
        pl.add(Projections.property("contenutoBlob"), "contenutoBlob");
        pl.add(Projections.property("id"), "id");
        criteria.setProjection(pl);
        criteria.setResultTransformer(Transformers.aliasToBean(AllegatoModelBlobDto.class));
        Session sessione = sf.getCurrentSession();
        List<AllegatoModelBlobDto> result = criteria.getExecutableCriteria(sessione).list();
        sw.stop();
        StopWatchUtils.printStopWatchInfo(sw, logger, false, "QUERY ESEGUITA CORRETTAMENTE. RECORD TROVATI "+result.size()+" RECUPERATO CORRETTAMENTE");
        if (result.size() > 1)
        {
            throw new IllegalStateException("Impossibile proseguire trovati " + result.size() + "record per l'ID " + id);
        }
        AllegatoModelBlobDto theObj = result.get(0);
        if (theObj != null)
        {
            Blob contenuto = theObj.getContenutoBlob();

            if (contenuto != null)
            {
                sw.start("SCRITTURA FILE SU OUTPUT STREAM");
                is = contenuto.getBinaryStream();
                IOUtils.copy(is, out);
                sw.stop();
                StopWatchUtils.printStopWatchInfo(sw, logger, false, "SCRITTURA FILE TERMINATA CORRETTAMENTE");
            }
        }

    }
    catch (Exception e)
    {
        String message = "Errore nel recupero dell'allegato con ID " + id;
        logger.error(message, e);
        throw new PinfGpDbException(message, e);
    }
    finally
    {
        if(sw.isRunning())
        {
            sw.stop();
            StopWatchUtils.printStopWatchInfo(sw, logger, true, "POSSIBILE ERRORE NELLA SCRITTURA DEL FILE");
        }
        if( is != null )
        {
            try
            {
                is.close();
            }
            catch (Exception e)
            {
                //Stampo lo stacktrace solo quando il log ha livello di debug
                if( logger.isDebugEnabled() )
                {

                    logger.debug("Errore nella chiusura del file input stream ", e);
                }
                else if( logger.isWarnEnabled() )
                {
                    logger.debug("Errore nella chiusura del file input stream; "+e.getMessage());
                }
            }
        }
        if( out != null )
        {
            try
            {
                out.close();
            }
            catch (Exception e)
            {
                //Stampo lo stacktrace solo quando il log ha livello di debug
                if( logger.isDebugEnabled() )
                {

                    logger.debug("Errore nella chiusura dell'output stream ", e);
                }
                else if( logger.isWarnEnabled() )
                {
                    logger.debug("Errore nella chiusura dell'output stream; "+e.getMessage());
                }
            }
        }
    }
}
Angelo Immediata
  • 6,635
  • 4
  • 33
  • 65
  • i am not using hibernate annotations. Assume you are using hibernate mapping,how you can acheive @lob in hibernate mapping? – Ravi Mar 22 '17 at 14:30
  • Thanks for your update. But i am not using binary type. I am using type blob as shown here. in postgres – Ravi Mar 22 '17 at 15:01
  • There is no blob type in HIbernate. The type `org.hibernate.type.BinaryType` tells hibernate to manage this property as a binary object; then you in your ode can use java.sql.Blob or the implementation of your RDBMS – Angelo Immediata Mar 22 '17 at 15:03
  • we are using type="java.sql.Blob" . Binary type having limitations in image handling.if you use blob type it extends up to 2gb in saving to database.Binary type wont extend up to 2gb. As per postgres documentations. – Ravi Mar 22 '17 at 15:06
  • at this point try to use `type=org.hibernate.type.BlobType` you can give a look to all hibernate types here https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/type/package-summary.html – Angelo Immediata Mar 22 '17 at 15:09
  • can you please check the below link. If i am wrong correct me.http://www.e2college.com/subjects/java_programming/tutorials/hibernate_native_api_with_mysql_tutorial/hibernate_entity_table_mapping_types.html – Ravi Mar 22 '17 at 15:47
  • The link is showing to you the "mapping" between Hibernate types and DB types. In your case you want to handle a java.sql.Blob object by using hibernate. So you must tell hibernate: my dear hibernate this field is a Blob. How can you tell hibernate this? You can by using the right hibernate type. So by using the XML fragment I showed you are saying: this is a property to persist and it is a Blob – Angelo Immediata Mar 22 '17 at 15:50
  • Okay. If will use org.hibernate.type.BlobType in xml mapping. Then will it be equivalent to @Lob annotation. Is there any other stuff i need to do in my pojo class (Mapping class file for Blob setter and getter)i.e., getBlob and setBlob methods enough to get Blob object – Ravi Mar 22 '17 at 15:56
  • As far as I know it should be sufficient what I wrote no other stuffs in your pojo... let me know if it works.... – Angelo Immediata Mar 22 '17 at 15:57
  • it is working but still having some doubts. If blob object i am using in different table then it is working. In the same table if i use blob then it is not working. Blob.getlength() coming as zero. Hospital table i have a column hospital_image. when i want to fetch the image by using hospital object then it is not working. Blob.lenght() coming zero. So i can't able to write . – Ravi Mar 25 '17 at 10:28
  • int dataSize; InputStream is = mainImageBlob.getBinaryStream(); try { while ((dataSize = is.read(buf)) != -1) { baos.write(buf, 0, dataSize); } } . For suppose if i create a new table called file table and i have a relation like this. One hospital having many images. Then blob.getlength() is working fine. I dont know why it is not working with in the same object. I need to use a different transaction to get the image if i use the same transaction with in the same table? – Ravi Mar 25 '17 at 10:28
  • try to update your question by adding your code. In any case as far as I know you should be inside hibernate session to operate with Blob – Angelo Immediata Mar 25 '17 at 12:32
  • I have updated my code. saving hospital object is working fine. I can see the hospital_image (oid) column got some numeric values. Where as while fetching the hospital object. i am not using any session or Transaction. Do you want me to use any session or Transaction. Please help me here. I dont have any idea why it is not working. – Ravi Mar 26 '17 at 18:53
  • @Ravi I guess this is off topic respect to the question.. in any case see the update 2 where i wrote what i usually do to save and write Blobs – Angelo Immediata Mar 27 '17 at 07:51
0

Use the basic tag and add the lob tag inside:

    <basic name="lobcolumn">
        <column name="lob_column"/>
        <lob/>
    </basic>
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
0

type is blob. it maps to hibernate pojo with Blob data type.Both will match and it saves your image as well.

In hbm.xml u

property name="contentualblob" type="blob"

Ravi
  • 159
  • 3
  • 17