hibernate中映射blob數據類型的一個例子 (zhuan)
1
java 代碼
2
public class User implements java.io.Serializable {
3
4
5
// Fields
6
7
private long id;
8
private String name;
9
private String email;
10
private String addr;
11
//定義Blob的pthto
12
private Blob photo;
13
14
xml 代碼
15
<hibernate-mapping>
16
<class name="org.tie.User" table="user" catalog="tie">
17
<id name="id" type="long">
18
<column name="id" />
19
<generator class="identity" />
20
</id>
21
<property name="name" type="string">
22
<column name="name" length="45" not-null="true" />
23
</property>
24
<property name="email" type="string">
25
<column name="email" length="45" />
26
</property>
27
<property name="addr" type="string">
28
<column name="addr" length="45" />
29
</property>
30
<!-- 映射blob類型 -->
31
<property name="photo" type="blob">
32
<column name="photo" />
33
</property>
34
</class>
35
</hibernate-mapping>
36
37
兩個測試方法:
38
39
java 代碼
40
public void testCreate(){
41
42
User user = new User();
43
user.setName("linweiyang");
44
user.setAddr("beijing");
45
user.setEmail("linweiyang@163.com");
46
Blob photo = null;
47
48
try {
49
//將圖片讀進輸入流
50
FileInputStream fis = new FileInputStream("c:\\a.jpg");
51
//轉成Blob類型
52
photo = Hibernate.createBlob(fis);
53
54
} catch (FileNotFoundException e) {
55
e.printStackTrace();
56
} catch (IOException e) {
57
e.printStackTrace();
58
}
59
60
user.setPhoto(photo);
61
62
Session session = factory.openSession();
63
Transaction tr = session.beginTransaction();
64
session.save(user);
65
tr.commit();
66
session.close();
67
68
}
69
70
public void testRerieve(){
71
72
Session session = factory.openSession();
73
User user = (User)session.load(User.class, new Long(3));
74
try {
75
//從數據庫中要讀取出來
76
InputStream is = user.getPhoto().getBinaryStream();
77
//在把寫到一個圖片格式的文件里
78
FileOutputStream fos = new FileOutputStream("c:\\linweihan.jpg");
79
80
byte[] buffer = new byte[1024];
81
int len = 0;
82
//從數據庫中讀取到指定的字節數組中
83
while((len = is.read(buffer) )!= -1){
84
//從指定的數組中讀取,然后輸出來,所以這里buffer好象是連接inputStream和outputStream的一個東西
85
fos.write(buffer,0,len);
86
}
87
} catch (FileNotFoundException e) {
88
e.printStackTrace();
89
} catch (SQLException e) {
90
e.printStackTrace();
91
} catch (IOException e){
92
e.printStackTrace();
93
}
94
session.close();
95
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

這么理解輸入輸出流
讀入流,自然要有讀入的源頭,
輸出也要輸出到某個地方,輸出一般是先要輸讀入,
這里連接輸入和輸出的是一個在內存中的字節數組buffer.這樣從數據庫中讀到這個數組里,輸出流在從這個數組中輸出到特定的文件格式里.
posted on 2007-12-17 16:25 都市淘沙者 閱讀(2018) 評論(1) 編輯 收藏 所屬分類: Hibernate/ORM