Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

java - proper hibernate mapping for @lob in Hibernate pojo. we are using hibernate mapping. can you please tell me equivalent for @lob annotation

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...