理论上有这两种方法:
1.那我保存记录时,转化数据类型。但是该怎么转化?2.或者是手工改配置文件里的String为Blob??行得通吗?希望各位多提建议,当然详细一点更好。
最后,请分析一下这两种方法的优缺点,可以从各个方面考虑,如占用存储空间大小,存储效率等。

解决方案 »

  1.   

    在Hibernate中,您可以直接对Blob、Clob作映像,例如在MySQL中,您的数据库表格若是这么建立的: CREATE TABLE user ( id INT(11) NOT NULL auto_increment PRIMARY KEY, name VARCHAR(100) NOT NULL default '', age INT, photo BLOB, resume Text )engine=innodb; 您可以定义一个User类别,并让属性包括java.sql.Blob与java.sql.Clob,如下: User.java package onlyfun.caterpillar; import java.sql.Blob; import java.sql.Clob; public class User { private Integer id; private String name; private Integer age; private Blob photo; private Clob resume; // 必须要有一个预设的建构方法 // 以使得Hibernate可以使用Constructor.newInstance()建立对象 public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Blob getPhoto() { return photo; } public void setPhoto(Blob photo) { this.photo = photo; } public Clob getResume() { return resume; } public void setResume(Clob resume) { this.resume = resume; } } 接着在映射文件中,可以如下定义: User.hbm.xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="onlyfun.caterpillar.User" table="user"> <id name="id" column="id" type="java.lang.Integer">   <generator class="native"/> </id> <property name="name" column="name" type="java.lang.String"/> <property name="age" column="age" type="java.lang.Integer"/> <property name="photo" column="photo" type="java.sql.Blob"/>   <property name="resume" column="resume" type="java.sql.Clob"/> </class> </hibernate-mapping> 在进行数据储存时,可以使用Hibernate.createBlob()与Hibernate.createClob()从来源数据建立Blob与Clob实例,例如: FileInputStream fileInputStream = new FileInputStream("c:\\workspace\\photo.jpg"); Blob photo = Hibernate.createBlob(fileInputStream); Clob resume = Hibernate.createClob("Bla....Bla....resume text!!"); User user = new User(); user.setName("caterpillar"); user.setAge(new Integer(30)); user.setPhoto(photo); user.setResume(resume); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.save(user); tx.commit(); session.close(); 如果打算从数据库中取得数据,则一个范例如下所示: Session session = sessionFactory.openSession(); User user = (User) session.load(User.class, new Integer(1)); System.out.print(user.getAge() + "\t" +         user.getName() + "\t"); String resume = user.getResume().getSubString(1, (int) user.getResume().length()); System.out.println(resume);     // 将Blob数据写到档案 InputStream inputStream = user.getPhoto().getBinaryStream(); FileOutputStream fileOutputStream = new FileOutputStream("c:\\workspace\\photo_save.jpg"); byte[] buf = new byte[1]; int len = 0; while((len = inputStream.read(buf)) != -1) { fileOutputStream.write(buf, 0, len); } inputStream.close(); fileOutputStream.close(); System.out.println("save photo to c:\\workspace\\photo_save.jpg"); session.close(); 在MySQL中对Blob与Clob是比较简单的,如果在Oracle DB中则复杂一些,您可以参考 Using Clobs/Blobs with Oracle and Hibernate。
      

  2.   

    但是UserDAO.java里面的内容要做哪些更改?
      

  3.   

    package com.hepeng.events;import java.sql.Blob;
    import java.util.List;
    import java.util.Set;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.hibernate.LockMode;
    import org.hibernate.Query;
    import org.hibernate.criterion.Example;/**
     * A data access object (DAO) providing persistence and search support for
     * Examinee entities. Transaction control of the save(), update() and delete()
     * operations can directly support Spring container-managed transactions or they
     * can be augmented to handle user-managed Spring transactions. Each of these
     * methods provides additional information for how to configure it for the
     * desired type of transaction control.
     * 
     * @see com.hepeng.events.Examinee
     * @author MyEclipse Persistence Tools
     */public class ExamineeDAO extends BaseHibernateDAO {
    private static final Log log = LogFactory.getLog(ExamineeDAO.class);
    // property constants
    public static final String IDENTITY_CARD_ID = "identityCardId";
    public static final String CERTIFICATE_ID = "certificateId";
    public static final String NAME = "name";
    public static final String DEPARTMENT = "department";
    public static final String SEX = "sex";
    public static final String AGE = "age";
    public static final String PHOTO = "photo"; public void save(Examinee transientInstance) {
    log.debug("saving Examinee instance");
    try {
    getSession().save(transientInstance);
    log.debug("save successful");
    } catch (RuntimeException re) {
    log.error("save failed", re);
    throw re;
    }
    } public void delete(Examinee persistentInstance) {
    log.debug("deleting Examinee instance");
    try {
    getSession().delete(persistentInstance);
    log.debug("delete successful");
    } catch (RuntimeException re) {
    log.error("delete failed", re);
    throw re;
    }
    } public Examinee findById(java.lang.Integer id) {
    log.debug("getting Examinee instance with id: " + id);
    try {
    Examinee instance = (Examinee) getSession().get(
    "com.hepeng.events.Examinee", id);
    return instance;
    } catch (RuntimeException re) {
    log.error("get failed", re);
    throw re;
    }
    } public List findByExample(Examinee instance) {
    log.debug("finding Examinee instance by example");
    try {
    List results = getSession().createCriteria(
    "com.hepeng.events.Examinee").add(Example.create(instance))
    .list();
    log.debug("find by example successful, result size: "
    + results.size());
    return results;
    } catch (RuntimeException re) {
    log.error("find by example failed", re);
    throw re;
    }
    } public List findByProperty(String propertyName, Object value) {
    log.debug("finding Examinee instance with property: " + propertyName
    + ", value: " + value);
    try {
    String queryString = "from Examinee as model where model."
    + propertyName + "= ?";
    Query queryObject = getSession().createQuery(queryString);
    queryObject.setParameter(0, value);
    return queryObject.list();
    } catch (RuntimeException re) {
    log.error("find by property name failed", re);
    throw re;
    }
    } public List findByIdentityCardId(Object identityCardId) {
    return findByProperty(IDENTITY_CARD_ID, identityCardId);
    } public List findByCertificateId(Object certificateId) {
    return findByProperty(CERTIFICATE_ID, certificateId);
    } public List findByName(Object name) {
    return findByProperty(NAME, name);
    } public List findByDepartment(Object department) {
    return findByProperty(DEPARTMENT, department);
    } public List findBySex(Object sex) {
    return findByProperty(SEX, sex);
    } public List findByAge(Object age) {
    return findByProperty(AGE, age);
    } //其实没有这个需求
    public List findByPhoto(Object photo) {
    return findByProperty(PHOTO, photo);
    } public List findAll() {
    log.debug("finding all Examinee instances");
    try {
    String queryString = "from Examinee";
    Query queryObject = getSession().createQuery(queryString);
    return queryObject.list();
    } catch (RuntimeException re) {
    log.error("find all failed", re);
    throw re;
    }
    } public Examinee merge(Examinee detachedInstance) {
    log.debug("merging Examinee instance");
    try {
    Examinee result = (Examinee) getSession().merge(detachedInstance);
    log.debug("merge successful");
    return result;
    } catch (RuntimeException re) {
    log.error("merge failed", re);
    throw re;
    }
    } public void attachDirty(Examinee instance) {
    log.debug("attaching dirty Examinee instance");
    try {
    getSession().saveOrUpdate(instance);
    log.debug("attach successful");
    } catch (RuntimeException re) {
    log.error("attach failed", re);
    throw re;
    }
    } public void attachClean(Examinee instance) {
    log.debug("attaching clean Examinee instance");
    try {
    getSession().lock(instance, LockMode.NONE);
    log.debug("attach successful");
    } catch (RuntimeException re) {
    log.error("attach failed", re);
    throw re;
    }
    }
    }
      

  4.   

    如果是二进制数据,改成 byte[] 吧如果是大的文本文件,用 String 没问题。
      

  5.   

    这个设置其实很简单,在myeclipse生成pojo的时候,他提供了手工设置类型mapping的功能。只要在生成之前,按照你想要的类型匹配来匹配的话,应该就可以了。
      

  6.   

    晕哦,我在设置的时候,一看太麻烦,就把它跳过去了-_-!!。谢谢竹子,不过我还是打算使用blob,目的是为了学习blob。
    结贴啦!