복붙노트

[SPRING] Hibernate pojo에서 @lob을위한 적절한 하이버 네이트 매핑. 우리는 최대 절전 모드 매핑을 사용하고 있습니다. 당신은 제게 @lob annotation을 말해 줄 수 있습니까?

SPRING

Hibernate pojo에서 @lob을위한 적절한 하이버 네이트 매핑. 우리는 최대 절전 모드 매핑을 사용하고 있습니다. 당신은 제게 @lob annotation을 말해 줄 수 있습니까?

최대 절전 모드 매핑을 사용하고 있습니다. 최대 절전 모드 구성 파일에는 type = "blob"및 pojo 클래스 getBlob 및 setBlob 메서드가 있습니다. 이 외에도 우리는 @lob 권한을 가져야합니다. 최대 절전 모드 매핑에서 lob에 해당하는 것은 무엇입니까?

@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. ==============================

    1.내 모델에서는 다음을 사용하고 있습니다.

    내 모델에서는 다음을 사용하고 있습니다.

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

    주석 @Lob은 Lob 열임을 나타냅니다. @Basic (fetch = FetchType.LAZY)은 Lob을 메모리에로드하지 않고 엔티티를로드하도록 지시합니다. 정말로 필요할 때만 로브에 접근 할 수 있습니다.

    최신 정보

    오랜 시간 XML을 사용하지는 않지만 잘못된 것이 아니라면 다음과 같이 사용할 수 있습니다.

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

    업데이트 2

    hibernateTemplate을 절대로 사용하지 않았다면 hibernateTemplate을 사용하여 최대 절전 모드 세션에 액세스 할 수있다. 대개 다음과 같이합니다.

    Blob 메서드 저장

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

    BLOB 메소드 가져 오기

    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. ==============================

    2.기본 태그를 사용하고 내부에 lob 태그를 추가하십시오.

    기본 태그를 사용하고 내부에 lob 태그를 추가하십시오.

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

    3.type은 blob입니다. 그것은 Blob 데이터 타입으로 최대 절전 모드로 매핑됩니다. 모두 일치 할 것이고 이미지도 저장됩니다.

    type은 blob입니다. 그것은 Blob 데이터 타입으로 최대 절전 모드로 매핑됩니다. 모두 일치 할 것이고 이미지도 저장됩니다.

    hbm.xml에서

    속성 이름 = "contentualblob"type = "blob"

  4. from https://stackoverflow.com/questions/42950938/proper-hibernate-mapping-for-lob-in-hibernate-pojo-we-are-using-hibernate-mapp by cc-by-sa and MIT license