用Hibernate写入image到blob字段后,读出不稳定

我的环境是Struts 1.1 + Hibernate 3 + Mysql 5.0.??,这段程序包括两部分,一是上传图片文件,二是在另一页显示,使用LONGBLOB存储图片(image字段)。
现在的问题是上传图片没问题,但图片显示时新上传的图片有时可以显示全部,有时不可以,而且一旦有一张显示不正确,则新上传的图片就不在返回列表中了,好像Hibernate从cache中把它们剔除了,但是系统重启动后就可以显示所有记录了。后台报如下错误:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [data.hibernate.dataobject.main.sales.Walltile#50]
指出id为50的Walltile对象不存在,事实上数据库中是有的。

部分相关的代码工作流程如下:
1.取出记录总数
2.取出记录,但不访问image字段,只把所有id传回客户端,客户端据此请求每个图片
3.服务器端接受客户端发来的针对每个图片的请求,此时用session.load()得到每条记录,然后访问图片并传回


1.取记录总数如下:


public int getPagesOfTiles(String cond)
{
Session session = HibernateSessionFactory.currentSession();
try {
Integer records = (Integer)session.createQuery("select count(tile.id) from Walltile tile").uniqueResult();
if (records.intValue() % 10 == 0) // 每页10条记录
return records.intValue() / 10;
else
return (records.intValue() / 10 + 1);

}
catch (Exception e)
{
log.error(e);
e.printStackTrace();
}
finally {
session.close();
}
return 0;
}

2.取出所有记录id部分如下:


public List getWalltiles(Integer startPos)
{
Session session = HibernateSessionFactory.currentSession();
try {
// 取出所有记录(测试)
List tiles = session.createCriteria(Walltile.class).setFirstResult(startPos.intValue()*10).setMaxResults(10).list();
return tiles;
}
catch (Exception e)
{
log.error(e);
e.printStackTrace();
}
finally {
session.close();
}
return null;
}

3.服务器端根据每个id查找记录并返回图片,这段代码我特意将其放在Action中以测试:


String tid = request.getParameter("tid");

Walltile tile = null;
Session session = HibernateSessionFactory.currentSession();
try {
tile = (Walltile)session.load(Walltile.class, Integer.valueOf(tid));

java.sql.Blob image = tile.getImage();

// output image to client
response.setContentType("image/jpeg");
response.setContentLength((int)image.length());
OutputStream output = response.getOutputStream();
output.write(image.getBytes(1, (int)image.length()));
output.flush();
output.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
session.close();
}

4.Walltile.hbm.xml定义如下:


<hibernate-mapping>
<class name="data.hibernate.dataobject.main.sales.Walltile" table="walltile">
<id name="id" type="integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="string">
<column name="name" length="45" />
</property>
<property name="description" type="string">
<column name="description" length="45" />
</property>
<property name="image" type="java.sql.Blob" lazy="false">
<column name="tileimage" not-null="true"/>
</property>
</class>
</hibernate-mapping>

并且我也试了将Hibernate类型改为binary,image属性为byte[],也是不行,没有办法了,希望各位帮帮忙了!
Hibernate有自己的缓存的。可能太多图片占据内存了。
1. 关闭Hibernate缓存。
2. 自己使用Jdbc读取,然后自己放入缓存。