`
xinlnix
  • 浏览: 3324 次
  • 来自: ...
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

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

阅读更多
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,仍为乱码,估计应该是乱码。如何正确编码?
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics