【发布时间】:2018-08-13 23:38:24
【问题描述】:
我正在尝试让我的代码加载图片并将其保存在 DB2 中。我不确定下一步该怎么做,因为下面的代码失败了。有人可以指导我如何做到这一点。我已经从数据库生成了一个实体。文档名(实际文件)的数据类型是 blob,但是当我生成实体时,它显示为 byte[]。下面的方法在 EJB 中。
@Entity
@Table(name = "DOCUMENTS", schema = "PORTAL")
public class Documents {
private int documentid;
private byte[] documentname;
@Id
@Column(name = "DOCUMENTID", nullable = false)
public int getDocumentid() {
return documentid;
}
public void setDocumentid(int documentid) {
this.documentid = documentid;
}
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "DOCUMENTNAME", nullable = true)
public byte[] getDocumentname() {
return documentname;
}
public void setDocumentname(byte[] documentname) {
this.documentname = documentname;
}
在这里,我正在尝试阅读或加载图片。
private byte[] readImage(String filename) {
byte[] imageData = null;
FileInputStream file = null;
try {
file = new FileInputStream(filename);
int size = file.available();
imageData = new byte[size];
file.read(imageData);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (file != null) file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return imageData;
}
这基本上是我认为我失去它的地方。
public Boolean populateProfilePicture(int blobFileID, byte[] blobFIle) {
Connection con = null;
PreparedStatement pstmt = null;
int success = 0;
String empPhotoFile = "/home/mika/Pictures";
Documents fileTable = new Documents();
try {
con = dataSource.getConnection();
pstmt = con.prepareStatement("INSERT INTO Documents VALUES(?,?)");
pstmt.setInt(1, blobFileID);
pstmt.setBytes(2, readImage(empPhotoFile));
success = pstmt.executeUpdate();
} catch (SQLException e) {
try {
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
if (success>=1)
{
return true;
}
return true;
}
【问题讨论】:
标签: java jpa db2 ejb prepared-statement