Search code examples
javahibernateblobdozer

Hibernate: Avoid persisting field during merge()


I have a webapp where users can upload files (via multipart/form-data), and they get stored along with their metadata in a DB with Hibernate (@Entity class Document).

The target table has a BLOB column content where the contents of the files are saved. Users who upload files are then allowed to modify some of the metadata (e.g. the original file name) in a GWT-based UI. To that end, I use Dozer to convert Document instance into a ClientDocument instance, which does not have the content field and is serializable for GWT. Once a modified ClientDocument instance arrives from the browser, I convert it back into Document and execute this:

ClientDocument document = ...;
Document entity = dozerBeanMapper.map(document, Document.class);
Session session = sessionFactory.getCurrentSession();
session.merge(entity);

At this point the entity's content column gets cleared, since Dozer, obviously, did not fill in the corresponding BLOB data.

Is there any way to avoid updating this particular BLOB content column during merge()? I have seen Not committing an hibernate entity field to the DB, but the @Transient solution does not work for me, since I need to fetch the content BLOB for other operations in the backend.

Any suggestions?


Solution

  • You can tell Hibernate not to update the field at all

    <property name="fieldName" insert="true" update="false"/>
    

    Using annotations it will be something like this:

    @Column(insertable = true, updatable = false)
    

    Note, that the field is insertable which means it will be inserted, but next time you're going to update the entity, it won't be updated.