我想将我的文件保存在 Oracle 实例上。我正在使用 Hibernate 来处理数据对象。如何将文件插入 Oracle Blob。有这方面的示例代码吗?
最佳答案
首先,您必须使用 @javax.persistance.Lob 注释来注释您的实体字段。 像这样:
public class InfoMessage {
private byte[] body;
@Lob
public byte[] getBody() {
return body;
}
public void setBody(byte[] body) {
this.body = body;
}
}
并用字节数组设置它。这取决于您使用的 File 类。 java.io.File 的第一个 google 结果。我想这个操作有更好的解决方案。
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
关于java - 我想通过 Hibernate 使用 BLOB 列类型将文件插入到 Oracle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1243706/