Hibernate:挑出一列包含不应加载的二进制数据的列


问题内容
  • 我正在研究Spring-MVC应用程序,并将Hibernate用作PostgreSQL的ORM工具。目前,我想在数据库中保存一些文件。为此,我有一个Attachments类,该类与Notes类具有多对一映射。
    • 现在在附件类中,我还具有要显示的文件名,上载者名称等,但不以EAGER加载或从数据库中获取对象为代价,这会随附件一起拖动附件。是否有任何选项可排除二进制数据列,因此不会加载该列。代码如下:

附件型号:

@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
}

附件DAOImpl:

 @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;
        }
    }

另外,如果我将PDF保存在数据库中,是否需要对它执行一些额外的操作才能正确获取数据。我的意思是,当我过去保存图像时,必须在图像数据之前添加“
data:image / png; base64”。我希望不需要这样的东西。你能帮忙的话,我会很高兴。非常感谢。


问题答案:

之一

  1. 延迟加载字段

@Basic(fetch = FetchType.LAZY)向您的字段添加注释。您将需要字节码检测。请参阅http://java.dzone.com/articles/hibernate-
bytecode-enhancement
以获取帮助

  1. 使该字段成为自己的类,并使其成为one2one关系。然后让那个懒

  2. 您也许可以与同一个班级建立one2one关系?然后让那个懒

对于第二个问题,您应该将contentType上载文件的保存在数据库中,并在使用进行下载时将其写回response.setHeader('Content- Type', ...);