Total Pageviews

2017/10/07

Using JPA to Insert and Retrieve BLOBs

Problem
I am using JPA to do CRUD in persistence tier. If I would like to insert an image file into Microsoft SQL Server, how to do it?

The table schema is the following:
CREATE TABLE "CAM_CAMPAIGN_IMGS"
(
   CAMPAIGN_ID nvarchar(10) NOT NULL,
   CID nvarchar(100) NOT NULL,
   IMAGE varbinary(MAX) NOT NULL,
   CONTENT_TYPE nvarchar(100) NOT NULL,
   CONSTRAINT PK_CAM_CAMPAIGN_IMGS PRIMARY KEY (CAMPAIGN_ID, CID)
)
GO


How-To
You can see image column add @Lob annotation in entity class:
package com.xxx.ecp.commons.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;


@Entity
@Table(name="CAM_CAMPAIGN_IMGS")
public class CamCampaignImg implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private CamCampaignImgPK id;

    @Column(name="CONTENT_TYPE")
    private String contentType;

    @Lob
    @Column(name="IMAGE")
    private byte[] image;

    public CamCampaignImg() {
    }

    public CamCampaignImgPK getId() {
        return this.id;
    }

    public void setId(CamCampaignImgPK id) {
        this.id = id;
    }

    public String getContentType() {
        return this.contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public byte[] getImage() {
        return this.image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

}


Code snippet regarding insert image file looks like:
     CamCampaignImgPK imgPK = new CamCampaignImgPK();
     imgPK.setCampaignId(camCampaign.getCampaignId());
     imgPK.setCid(form.getImgFileName());
     
     CamCampaignImg camCampaignImg = new CamCampaignImg();
     camCampaignImg.setId(imgPK);
     camCampaignImg.setContentType(form.getContentType());
     
     // convert to bytes from input stream
     camCampaignImg.setImage(form.getImgFile().getBytes());
     
     camCampaiganImgRep.create(camCampaignImg);


Code snippet about retrieve image file looks like:
     List<CamCampaignImg> imgs = camCampaignImgRepCust.findByCampaignId(campaign.getCampaignId());
     for(CamCampaignImg img : imgs) {
        // get image's content type
        String contentType = img.getContentType();
        // get image file's input stream
        InputStream imgInputStream = new ByteArrayInputStream(img.getImage());
     }


No comments: