论坛首页 Java企业应用论坛

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

浏览 3303 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-02-28  
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,仍为乱码,估计应该是乱码。如何正确编码?
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics