将文本文件写入Hibernate的CLOB字段,中文乱码如何解决?

本文介绍了一个关于MySQL数据库中大文本字段resume出现乱码的问题及解决方案。通过使用Hibernate框架创建Clob对象来存储大文本数据,并探讨了如何确保文件正确编码的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mysql 5.0数据库mydb
CREATE DATABASE mydb
CHARACTER SET 'utf8'
COLLATE 'utf8_general_ci';

表employee:
create table employee (
id integer not null auto_increment,
firstname varchar(15),
........
resume text,
primary key (id)
)ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

employee.hbm.xml
<class name="Employee"  table="employee">
<id name="id" type="java.lang.Integer" column="id">
<generator class="identity" />
</id>

<property name="firstname" type="java.lang.String" column="firstname" length="15"/>
....
<property name="resume" type="java.sql.Clob" column="resume" />

</class>

操作类Dao.java:
	public void importLargeObjects() {

String filename = null;
File file;
String rootPath ;

Session session = Dao.sessionFactory.openSession();
Query query = session.createQuery("from Employee");

List<?> list = query.list();
Iterator<?> it = list.iterator();
while (it.hasNext()) {
Employee employee = (Employee) it.next();

session.beginTransaction();
rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath().toString();
//取build/texts/目录下雇员名.txt为当前文件名,文本文件均以utf8编码。
filename = rootPath+"texts/" + employee.getFirstname() + ".txt";
file = new File(filename);
try {
FileReader reader = new FileReader(filename);
// 写入的文件不能过大,即要小于int最大值。
Clob resume = Hibernate.createClob(reader, (int) file.length());
employee.setResume(resume);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//file.delete();
session.save(employee);
session.getTransaction().commit();
}
session.close();
}


用MySQL Query Browser查看resume为乱码,怀疑可能是MySQL Query Browser问题,使用SQL Manager for MySQL 2007(4.1)查看resume,仍为乱码,估计应该是乱码。如何正确编码?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值