dimanche 1 mars 2015

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 :



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


@Id
@Column(name="attachid")
@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;


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

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

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


AttachmentsDAOImpl :



@Override
public boolean addAttachment(byte[] bytes, String fileName, int noteid) {
session = this.sessionFactory.getCurrentSession();
try {
Attachment attachment = new Attachment();
attachment.setFileName(fileName);
attachment.setAttachment(bytes);
attachment.setFileUploadDate(new Timestamp(System.currentTimeMillis()));
Notes notes = (Notes)session.get(Notes.class,noteid);
notes.getAttachments().add(attachment);
attachment.setNotedata(notes);
session.save(notes);
session.flush();
return true;
} catch (HibernateException e){
e.printStackTrace();
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.


Aucun commentaire:

Enregistrer un commentaire