Storing and writing Blob and Clob with hibernate

Source: Internet
Author: User

Person. java

package www.csdn.net.blank.bean;import java.io.Serializable;import java.sql.Blob;import java.sql.Clob;public class Person  implements Serializable{    /** *  */    private static final long serialVersionUID = 1L;    private Integer id;    private Blob image;    private Clob intro;    public Person() {super();}public Person(Integer id, Blob image, Clob intro) {super();this.id = id;this.image = image;this.intro = intro;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public Blob getImage() {return image;}public void setImage(Blob image) {this.image = image;}public Clob getIntro() {return intro;}public void setIntro(Clob intro) {this.intro = intro;}        }

Person. hbm. xml

 
      
      
         
              
               
            
         
            
          
       
  
 


BaseDao. java

Package www.csdn.net. blank. dao; import java. io. serializable; import java. util. list; @ SuppressWarnings ("rawtypes") public interface BaseDao {/*** save Object ** @ param entity */public void saveObject (Object entity ); /*** update Object ** @ param entity */public void updateObject (Object entity ); /*** Delete Object ** @ param entity */public void deleteObject (Object entity ); /*** Delete object objects by id ** @ param clazz * @ param id */public void deleteObjectById (Class clazz, Serializable id ); /*** query Object objects by id ** @ param clazz * @ param id * @ return */public Object loadObjectById (Class clazz, Serializable id ); /*** query Object objects by id ** @ param clazz * @ param id * @ return */public Object getObjectById (Class clazz, Serializable id ); /*** query all operations ** @ param clazz * @ return */public List getObjects (Class clazz );}

BaseDaoImpl. java

Package www.csdn.net. blank. dao. impl; import java. io. serializable; import java. util. arrayList; import java. util. list; import org. hibernate. session; import org. hibernate. transaction; import www.csdn.net. blank. dao. baseDao; import www.csdn.net. blank. util. required; @ SuppressWarnings ("rawtypes") public class BaseDaoImpl extends implements BaseDao {@ Overridepublic void saveObject (Object entity) {// obtain the session Object Session = getSessionObject (); // open the Transaction ts = session. beginTransaction (); try {// Save the session. save (entity); // submit the transaction ts. commit ();} catch (Exception e) {ts. rollback () ;}@ Overridepublic void updateObject (Object entity) {// obtain the session Object Session session = getSessionObject (); // open the Transaction ts = session. beginTransaction (); try {// Save the session. update (entity); // submit the transaction ts. commit ();} catch (Exception e) {ts. rollback () ;}@ Overridepublic void deleteObject (Object entity) {// obtain the session Object Session session = getSessionObject (); // open the Transaction ts = session. beginTransaction (); try {// Save the session. delete (entity); // submit the transaction ts. commit ();} catch (Exception e) {ts. rollback () ;}@ Overridepublic void deleteObjectById (Class clazz, Serializable id) {// obtain the session object Session session = getSessionObject (); // open the Transaction ts = session. beginTransaction (); try {// Save the session. delete (getObjectById (clazz, id); // submit the transaction ts. commit ();} catch (Exception e) {ts. rollback () ;}@ Overridepublic Object loadObjectById (Class clazz, Serializable id) {return null ;}@ Overridepublic Object getObjectById (Class clazz, Serializable id) {Object obj = null; session session = getSessionObject (); Transaction ts = session. beginTransaction (); try {obj = session. get (clazz, id); ts. commit ();} catch (Exception e) {ts. rollback () ;}return obj ;}@ Overridepublic List getObjects (Class clazz) {List list = new ArrayList (); Session session = getSessionObject (); Transaction ts = session. beginTransaction (); try {list = session. createQuery ("from" + clazz. getName ()). list (); ts. commit ();} catch (Exception e) {ts. rollback () ;}return list ;}}

HiberUtil. java

Package www.csdn.net. blank. util; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. boot. registry. standardServiceRegistryBuilder; import org. hibernate. cfg. configuration; import org. hibernate. service. serviceRegistry; public class HiberUtil {static Configuration cfg; static ServiceRegistry serviceRegistry; static SessionFactory sessionFactory; static {// create a Configuration object call. configure () method, default class/hibernate. cfg. xmlcfg = new Configuration (). configure (); // create a service object serviceRegistry = new StandardServiceRegistryBuilder (). applySettings (cfg. getProperties ()). build (); // create sessionFactory factory sessionFactory = cfg. buildSessionFactory (serviceRegistry);}/*** get the session object * @ return */public static Session openSession () {return sessionFactory. getCurrentSession ();}}

Hibernate. cfg. xml

 
 
  
   
   
    
Com. mysql. jdbc. Driver
   
   
   
    
Jdbc: mysql: // localhost: 3306/hiber3? UseUincode = true & characterEncoding = UTF-8
   
   
   
    
Root
   
   
   
    
Root
   
   
   
    
Org. hibernate. dialect. MySQLDialect
   
   
   
    
Thread
   
   
   
    
True
   
   
   
    
False
   
   
   
    
Update
   
   
   
  
 

PersonTest. java

Package www.csdn.net. blank. junit; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. fileReader; import java. io. fileWriter; import java. io. inputStream; import java. io. reader; import java. SQL. blob; import java. SQL. clob; import org. hibernate. hibernate; import org. junit. test; import www.csdn.net. blank. bean. person; import www.csdn.net. blank. dao. baseDao; import www. cs Dn.net. blank. dao. impl. baseDaoImpl; import www.csdn.net. blank. util. hiberUtil; public class PersonTest {private BaseDao baseDao = new BaseDaoImpl (); @ Testpublic void save () throws Exception {Person person Person = new Person (); file file = new File ("F :\\ \ Pictures \ character (2) \ 200.jpg"); FileInputStream FD = new FileInputStream (file ); file file1 = new File ("D: \ Mei \ csdn \ hibernate course \ code \ hiber7 = 1 \ src \ custom label .txt" ); Reader reader = new FileReader (file1); // The first method is to use sessionFactory for session. getCurrentSession (); process the person operation. setImage (Hibernate. getLobCreator (HiberUtil. openSession ()). createBlob (FCM, file. length (); person. setIntro (Hibernate. getLobCreator (HiberUtil. openSession ()). createClob (reader, file1.length (); // Method 2: the transaction must be enabled/* Session session = HiberUtil. openSession (); // Transaction ts = session. beginTransact Ion (); person. setImage (session. getLobHelper (). createBlob (FCM, file. length (); person. setDescription (session. getLobHelper (). createClob (reader, file1.length (); // ts. commit (); */baseDao. saveObject (person) ;}@ Testpublic void getObject () throws Exception {// query object Person person = (Person) baseDao by id. getObjectById (Person. class, 1); // determines whether the object is nullif (person! = Null) {// obtain Blob field Blob blob = person. getImage (); // obtain the input stream object InputStream is = blob based on the getBinaryStream () method of the blob Object. getBinaryStream (); // defines the written File file File = new file ("D: \ 12.jpg"); // writes the output stream FileOutputStream fos = new FileOutputStream (File ); // buffer byte [] buffer = new byte [1024]; // read length int len = 0; // read cyclically until the end of the file while (len = is. read (buffer ))! =-1) {// write fos. write (buffer, 0, len);} // close the stream fos. close (); is. close (); // obtain the Clob field Clob clob = person. getIntro (); // obtain the character input stream Reader r = clob Based on getCharacterStream () of the clob object. getCharacterStream (); // defines the written File file1 = new File ("D: \ 12.txt"); // creates the output stream object FileWriter fileWriter = new FileWriter (file1 ); // buffer char [] cbuf = new char [1024]; // read length int len1 = 0; // read cyclically until the end of the file while (len1 = r. read (cbuf ))! =-1) {// write fileWriter. write (cbuf, 0, len1);} // close stream fileWriter. close (); r. close ();}}}
Result After the save method is executed:

Result After the getObject method is executed:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.