-->

proper hibernate mapping for @lob in Hibernate poj

2020-02-14 20:06发布

问题:

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);
}

回答1:

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());
                }
            }
        }
    }
}


回答2:

Use the basic tag and add the lob tag inside:

    <basic name="lobcolumn">
        <column name="lob_column"/>
        <lob/>
    </basic>


回答3:

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"