Hibernate : Single out a column containing binary data which shouldn't be loaded

  • I am working on a Spring-MVC application and using Hibernate as the ORM tool with PostgreSQL. Currently I would like to save some files in the database. For that I have a class Attachments, which has a many-to-one mapping with class Notes.
    • Now in class Attachments, I also have fileName, uploader name, etc, which I would like to display, but not at the cost of EAGER loading or getting the object from database, which would drag the attachment along with it. Is there any option to exclude the column of binary data, so it is not loaded. Here goes the code :

Attachments model :

@Table(name = "attachments")
public class Attachment {

    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "attach_gen")
    @SequenceGenerator(name = "attach_gen",sequenceName = "attach_seq")
    private int attachid;

    @Column(name = "filename")
    private String fileName;

    @Column(name = "uploaddate")
    private Timestamp fileUploadDate;

    @Column(name = "attachmentdata")
    private byte[] attachment;

    @JoinColumn(name = "noteid")
    private Notes notedata;

    public void setNotedata(Notes notedata){this.notedata=notedata;}

    public Notes getNotedata(){return notedata;}
     //Getters and setters ommitted

AttachmentsDAOImpl :

    public boolean addAttachment(byte[] bytes, String fileName, int noteid) {
        session = this.sessionFactory.getCurrentSession();
        try {
            Attachment attachment = new Attachment();
            attachment.setFileUploadDate(new Timestamp(System.currentTimeMillis()));
            Notes notes = (Notes)session.get(Notes.class,noteid);
            return true;
        } catch (HibernateException e){
            return false;

Also, if I save for example a PDF in the database, do I need to perform some extra operations on it to get the data correctly. I mean when I used to save images, I had to prepend the image data with "data:image/png;base64," . I hope something like this is not required. Any help would be nice. Thanks a lot.


One of

  1. Lazy load the field

    Add @Basic(fetch = FetchType.LAZY) annotation to your field. You'll need bytecode instrumentation. See http://java.dzone.com/articles/hibernate-bytecode-enhancement for help

  2. Make the field its own class and make it a one2one relationship. Then make that lazy

  3. You might be able to make a one2one relationship to the same class? Then make that lazy

For your second question, you should save the contentType of the uploaded file in your db and write that back when downloading with response.setHeader('Content-Type', ...);

This video can help you solving your question :)
By: admin