hibernate问题:一个属性在数据库里是blob类型;但是在MyEclipse生成的DAO里面却是String

hepeng19861212 2008-09-20 08:07:05
mysql数据库里面有一个表examinee,它含有一个blob类型的属性photo.但是我在MyEclipse里面使用hibernate Reverse Engineering 来生成events时,产生的Examinee类的photo属性却是String类型的。

请问当往数据库保存记录时,对于类型不匹配这个问题,该怎么办?
...全文
261 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
hepeng19861212 2008-09-21
  • 打赏
  • 举报
回复
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;
}
}
}
hepeng19861212 2008-09-21
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 yongtree 的回复:]
这个设置其实很简单,在myeclipse生成pojo的时候,他提供了手工设置类型mapping的功能。只要在生成之前,按照你想要的类型匹配来匹配的话,应该就可以了。

[/Quote]
晕哦,我在设置的时候,一看太麻烦,就把它跳过去了-_-!!。谢谢竹子,不过我还是打算使用blob,目的是为了学习blob。
结贴啦!
yongtree 2008-09-21
  • 打赏
  • 举报
回复
这个设置其实很简单,在myeclipse生成pojo的时候,他提供了手工设置类型mapping的功能。只要在生成之前,按照你想要的类型匹配来匹配的话,应该就可以了。
老紫竹 2008-09-21
  • 打赏
  • 举报
回复
如果是二进制数据,改成 byte[] 吧
如果是大的文本文件,用 String 没问题。
lyf_sust 2008-09-21
  • 打赏
  • 举报
回复
mark
  • 打赏
  • 举报
回复
mark
hepeng19861212 2008-09-20
  • 打赏
  • 举报
回复
但是UserDAO.java里面的内容要做哪些更改?
蛋蛋の忧伤 2008-09-20
  • 打赏
  • 举报
回复
在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。
hepeng19861212 2008-09-20
  • 打赏
  • 举报
回复
理论上有这两种方法:
1.那我保存记录时,转化数据类型。但是该怎么转化?

2.或者是手工改配置文件里的String为Blob??行得通吗?

希望各位多提建议,当然详细一点更好。
最后,请分析一下这两种方法的优缺点,可以从各个方面考虑,如占用存储空间大小,存储效率等。

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧