The following is an example of hibernate BLOB Data Type ing.
Hibernate BLOB: Java code:
- Public ClassUserImplements
- Java. Io. serializable {
- // Fields
- Private LongID;
- PrivateString name;
- PrivateString email;
- PrivateString ADDR;
- // Define the pthto of blob
- PrivateBlob photo;
Hibernate BLOB: XML code:
- <Hibernate-mapping>
- <ClassName = "org. Tie. User" table = "user" catalog = "Tie">
- <IDName = "ID" type = "long">
- <ColumnName = "ID"/>
- <GeneratorClass = "Identity"/>
- </ID>
- <PropertyName = "name" type = "string">
- <ColumnName = "name" length = "45" not-null = "true"/>
- </Property>
- <PropertyName = "email" type = "string">
- <ColumnName = "email" length = "45"/>
- </Property>
- <PropertyName = "ADDR" type = "string">
- <ColumnName = "ADDR" length = "45"/>
- </Property>
- <! -- Map blob type -->
- <PropertyName = "photo" type = "blob">
- <ColumnName = "photo"/>
- </Property>
- </Class>
- </Hibernate-mapping>
Two Testing Methods:
Java code:
- Public void testcreate (){
- User user = new user ();
- User. setname ("linweiyang ");
- User. setaddr ("Beijing ");
- User. setemail ("linweiyang@163.com ");
- Blob photo = NULL;
- Try {
- // Read the image into the input stream
- Fileinputstream FCM = new fileinputstream ("C: \ a.jpg ");
- // Convert to blob type
- Photo = hibernate. createblob (FCM );
- } Catch (filenotfoundexception e ){
- E. printstacktrace ();
- } Catch (ioexception e ){
- E. printstacktrace ();
- }
- User. setphoto (photo );
- Session session = factory. opensession ();
- Transaction TR = session. begintransaction ();
- Session. Save (User );
- Tr. Commit ();
- Session. Close ();
- }
- Public void testrerieve (){
- Session session = factory. opensession ();
- User user = (User) Session. Load (user. Class, new long (3 ));
- Try {
- // Read from the database
- Inputstream is = user. getphoto (). getbinarystream ();
- // Write the file to an image format
- Fileoutputstream Fos = new fileoutputstream ("C: \ linweihan.jpg ");
- Byte [] buffer = new byte [1024];
- Int Len = 0;
- // Read the specified byte array from the database
- While (LEN = is. Read (buffer ))! =-1 ){
- // Read from the specified array and output it,
- So here buffer seems to be something that connects inputstream and outputstream.
- FOS. Write (buffer, 0, Len );
- }
- } Catch (filenotfoundexception e ){
- E. printstacktrace ();
- } Catch (sqlexception e ){
- E. printstacktrace ();
- } Catch (ioexception e ){
- E. printstacktrace ();
- }
- Session. Close ();
- }
In this way, the input and output streams must be read from the source and output to a certain place. Generally, the output must be read first, here, the input and output are connected to a buffer in the memory byte array. in this way, the database reads the array, and the output stream is output from this array to a specific file format. The above is an example of hibernate BLOB Data Type ing.
Address: http://developer.51cto.com/art/200906/130231.htm