java - 我想通过 Hibernate 使用 BLOB 列类型将文件插入到 Oracle?

标签 java oracle hibernate

我想将我的文件保存在 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/

相关文章:

java - Java 6 中的遍历文件树

java - 如何撤消添加到 ArrayList 的元素

database - PLS-00352 和 PLS-00201 通过 DB 链接

oracle - SQL开发人员: How to make log output from a trigger?

SQL模式匹配

mysql - Hibernate - 想要使用hibernate和springboot将网页与mysql数据库连接

java - 如何避免由于无法使用多重继承而导致重复代码。 hibernate

java - Spring Data Native 查询 Lob 列的有趣错误

java - 碰撞避免示例或帮助

java - JPA/hibernate : how to automatically update fields on entity update