Skip to content

Commit e6e0248

Browse files
authored
Merge pull request #16879 from Michaelin007/blob
https://jira.baeldung.com/browse/BAEL-7958
2 parents 62227f6 + 257b70c commit e6e0248

File tree

4 files changed

+158
-0
lines changed

4 files changed

+158
-0
lines changed
139 KB
Loading
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package storefileblob;
2+
3+
import java.io.IOException;
4+
import java.io.File;
5+
import java.io.FileInputStream;
6+
import java.io.ByteArrayOutputStream;
7+
import java.sql.ResultSet;
8+
import java.sql.Connection;
9+
import java.sql.DriverManager;
10+
import java.sql.PreparedStatement;
11+
import java.sql.Statement;
12+
import java.sql.SQLException;
13+
import java.io.FileOutputStream;
14+
import java.io.InputStream;
15+
16+
public class JdbcConnection {
17+
18+
public static Connection connect() throws SQLException {
19+
Connection connection = DriverManager.getConnection("jdbc:h2:./test", "sa", "");
20+
return connection;
21+
}
22+
23+
public static byte[] convertFileToByteArray(String filePath) throws IOException {
24+
File file = new File(filePath);
25+
try (FileInputStream fileInputStream = new FileInputStream(file); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
26+
byte[] buffer = new byte[1024];
27+
for (int len; (len = fileInputStream.read(buffer)) != -1; ) {
28+
byteArrayOutputStream.write(buffer, 0, len);
29+
}
30+
return byteArrayOutputStream.toByteArray();
31+
}
32+
}
33+
34+
public static boolean writeBlobToFile(String query, int paramIndex, int id, String filePath) throws IOException, SQLException {
35+
try (Connection connection = connect(); PreparedStatement statement = connection.prepareStatement(query)) {
36+
statement.setInt(paramIndex, id);
37+
try (ResultSet resultSet = statement.executeQuery(); FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath))) {
38+
while (resultSet.next()) {
39+
InputStream input = resultSet.getBinaryStream("picture");
40+
byte[] buffer = new byte[1024];
41+
int bytesRead;
42+
while ((bytesRead = input.read(buffer)) > 0) {
43+
fileOutputStream.write(buffer, 0, bytesRead);
44+
}
45+
}
46+
return true;
47+
}
48+
}
49+
}
50+
51+
public boolean createSchema() throws SQLException {
52+
String sql = """
53+
CREATE TABLE IF NOT EXISTS warehouses (
54+
id INTEGER PRIMARY KEY,
55+
name text NOT NULL,
56+
capacity REAL,
57+
picture BLOB
58+
);""";
59+
try (Connection connection = connect(); Statement stmt = connection.createStatement()) {
60+
stmt.execute(sql);
61+
return true;
62+
}
63+
}
64+
65+
public boolean insertFile(int id, String name, int capacity, String picture) throws SQLException, IOException {
66+
String insertSql = """
67+
INSERT INTO warehouses(id,name,capacity,picture) VALUES(?,?,?,?)
68+
""";
69+
try (Connection conn = connect()) {
70+
if (conn != null) {
71+
PreparedStatement stmt = conn.prepareStatement(insertSql);
72+
stmt.setInt(1, id);
73+
stmt.setString(2, name);
74+
stmt.setDouble(3, capacity);
75+
stmt.setBytes(4, convertFileToByteArray(picture));
76+
stmt.executeUpdate();
77+
return true;
78+
}
79+
}
80+
return false;
81+
}
82+
83+
public boolean insertFileAsStream(int id, String name, int capacity, String filePath) throws SQLException, IOException {
84+
String insertSql = """
85+
INSERT INTO warehouses(id,name,capacity,picture) VALUES(?,?,?,?)
86+
""";
87+
try (Connection conn = connect()) {
88+
if (conn != null) {
89+
PreparedStatement stmt = conn.prepareStatement(insertSql);
90+
stmt.setInt(1, id);
91+
stmt.setString(2, name);
92+
stmt.setDouble(3, capacity);
93+
File file = new File(filePath);
94+
try (FileInputStream fis = new FileInputStream(file)) {
95+
stmt.setBinaryStream(4, fis, file.length());
96+
stmt.executeUpdate();
97+
return true;
98+
}
99+
100+
}
101+
}
102+
return false;
103+
}
104+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package storefileblob;
2+
3+
import org.junit.Test;
4+
import org.junit.jupiter.api.BeforeAll;
5+
import org.junit.jupiter.params.ParameterizedTest;
6+
import org.junit.jupiter.params.provider.CsvSource;
7+
import java.io.IOException;
8+
import java.sql.SQLException;
9+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
10+
import static org.junit.jupiter.api.Assertions.assertTrue;
11+
12+
public class JdbcConnectionUnitTest {
13+
14+
private static final String TEST_FILE_PATH = "warehouse.png";
15+
private static final String RETRIEVED_FILE_PATH = "retrieve-warehouse.png";
16+
private static JdbcConnection jdbcConnection;
17+
String selectBlob = """
18+
SELECT picture FROM warehouses WHERE id=?
19+
""";
20+
21+
@BeforeAll
22+
public static void setUp() throws SQLException {
23+
jdbcConnection = new JdbcConnection();
24+
jdbcConnection.createSchema();
25+
}
26+
27+
@Test
28+
public void givenDatabaseSchema_whenJdbcConnectionIsEstablished_thenCreateSchema() throws SQLException {
29+
assertTrue(jdbcConnection.createSchema());
30+
}
31+
32+
@ParameterizedTest
33+
@CsvSource({ "1, 'Liu', 3000", "2, 'Walmart', 5000" })
34+
public void givenBlobFile_whenInsertingTheBlobFileAsByteArray_thenSuccessful(int id, String name, int capacity) throws SQLException, IOException {
35+
boolean result = jdbcConnection.insertFile(id, name, capacity, TEST_FILE_PATH);
36+
assertTrue(result);
37+
}
38+
39+
@ParameterizedTest
40+
@CsvSource({ "7, 'Dylan', 8000", "8, 'Jumia', 1000" })
41+
public void givenBlobFile_whenInsertingTheFileIntoTheDatabaseInChunks_thenSuccessful(int id, String name, int capacity) throws SQLException, IOException {
42+
boolean result = jdbcConnection.insertFileAsStream(id, name, capacity, TEST_FILE_PATH);
43+
assertTrue(result);
44+
}
45+
46+
@Test
47+
public void givenAnEntityWithBlob_whenReadingBlobAndConvertingItToFile_thenSuccessful() throws SQLException, IOException {
48+
boolean result = JdbcConnection.writeBlobToFile(selectBlob, 1, 2, RETRIEVED_FILE_PATH);
49+
byte[] expectedBytes = JdbcConnection.convertFileToByteArray(TEST_FILE_PATH);
50+
byte[] retrievedBytes = JdbcConnection.convertFileToByteArray(RETRIEVED_FILE_PATH);
51+
assertArrayEquals(expectedBytes, retrievedBytes);
52+
}
53+
54+
}
139 KB
Loading

0 commit comments

Comments
 (0)