1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.submitted.blobtest;
17
18 import static org.junit.jupiter.api.Assertions.assertEquals;
19 import static org.junit.jupiter.api.Assertions.assertTrue;
20
21 import java.io.Reader;
22 import java.util.List;
23
24 import org.apache.ibatis.BaseDataTest;
25 import org.apache.ibatis.io.Resources;
26 import org.apache.ibatis.session.SqlSession;
27 import org.apache.ibatis.session.SqlSessionFactory;
28 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
29 import org.junit.jupiter.api.BeforeAll;
30 import org.junit.jupiter.api.Test;
31
32 class BlobTest {
33 private static SqlSessionFactory sqlSessionFactory;
34
35 @BeforeAll
36 static void initDatabase() throws Exception {
37 try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/blobtest/MapperConfig.xml")) {
38 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
39 }
40
41 BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
42 "org/apache/ibatis/submitted/blobtest/CreateDB.sql");
43 }
44
45 @Test
46
47
48
49 void testInsertBlobThenSelectAll() {
50 try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
51 BlobMapper blobMapper = sqlSession.getMapper(BlobMapper.class);
52
53 byte[] myblob = { 1, 2, 3, 4, 5 };
54 BlobRecord blobRecord = new BlobRecord(1, myblob);
55 int rows = blobMapper.insert(blobRecord);
56 assertEquals(1, rows);
57
58
59 List<BlobRecord> results = blobMapper.selectAll();
60
61 assertEquals(1, results.size());
62 BlobRecord result = results.get(0);
63 assertEquals(blobRecord.getId(), result.getId());
64 assertTrue(blobsAreEqual(blobRecord.getBlob(), result.getBlob()));
65 }
66 }
67
68 @Test
69
70
71
72 void testInsertBlobObjectsThenSelectAll() {
73 try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
74 BlobMapper blobMapper = sqlSession.getMapper(BlobMapper.class);
75
76 Byte[] myblob = { 1, 2, 3, 4, 5 };
77 BlobRecord blobRecord = new BlobRecord(1, myblob);
78 int rows = blobMapper.insert(blobRecord);
79 assertEquals(1, rows);
80
81
82 List<BlobRecord> results = blobMapper.selectAllWithBlobObjects();
83
84 assertEquals(1, results.size());
85 BlobRecord result = results.get(0);
86 assertEquals(blobRecord.getId(), result.getId());
87 assertTrue(blobsAreEqual(blobRecord.getBlob(), result.getBlob()));
88 }
89 }
90
91 static boolean blobsAreEqual(byte[] blob1, byte[] blob2) {
92 if (blob1 == null) {
93 return blob2 == null;
94 }
95
96 if (blob2 == null) {
97 return blob1 == null;
98 }
99
100 boolean rc = blob1.length == blob2.length;
101
102 if (rc) {
103 for (int i = 0; i < blob1.length; i++) {
104 if (blob1[i] != blob2[i]) {
105 rc = false;
106 break;
107 }
108 }
109 }
110
111 return rc;
112 }
113 }