Hibernate连接Oracle数据库乱码问题
最近做了个项目,用的框架式Struts+Spring+Hibernate框架的,以前用这个框架连接的数据库都是GBK编码集的,这次连接的是Oracle AMERICAN_AMERICA.US7ASCII编码的,这样就导致项目运行后全是乱码,郁闷了很久,要是每个都自己写转码,实在是太累了,也很烦,所以就考虑是不是在Hibernate里通过什么方法使汉字编码正常。
经过多次尝试、找高手请教和网上的查找最后发现一种比较方便实用的方法:
首先定义一个GBKString替换默认的类型,在映射文件中使用该类型做为TYPE。
例如:
<property name="battrancode" column="battrancode" type="String" />
替换为:
<property name="battrancode" column="battrancode" type="com.nl.tsp.dao.GBKString" />
GBKString.java Java代码 package com.nl.tsp.dao; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import oracle.jdbc.driver.OracleTypes; import org.apache.commons.lang.builder.HashCodeBuilder; import org.hibernate.HibernateException; import org.hibernate.usertype.UserType; /** * @description * @author Jason Tseng * */ public class GBKString implements UserType { public GBKString() { super(); } public int[] sqlTypes() { return new int[] { OracleTypes.VARCHAR }; } public Class returnedClass() { return String.class; } public boolean equals(Object x, Object y) throws HibernateException { return (x == y) || (x != null && y != null && (x.equals(y))); } public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { String val = rs.getString(names[0]); if (null == val) { return null; } else { try { val = new String(val.getBytes("iso-8859-1"), "GBK"); } catch (UnsupportedEncodingException e) { throw new HibernateException(e.getMessage()); } return val; } } public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if (value == null) { st.setNull(index, OracleTypes.VARCHAR); } else { String val = (String)value; try { val = new String(val.getBytes("GBK"), "iso-8859-1"); } catch (UnsupportedEncodingException e) { throw new HibernateException(e.getMessage()); } st.setObject(index, val, OracleTypes.VARCHAR); } } public Object deepCopy(Object value) throws HibernateException { if (value == null) return null; return new String((String) value); } public boolean isMutable() { return false; } public Object assemble(Serializable arg0, Object arg1) throws HibernateException { // TODO Auto-generated method stub return null; } public Serializable disassemble(Object arg0) throws HibernateException { // TODO Auto-generated method stub return null; } public int hashCode(Object arg0) throws HibernateException { return HashCodeBuilder.reflectionHashCode(this); } public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException { // TODO Auto-generated method stub return null; } } 之后在Web.xml配置文件里,把过滤器设定为GBK的,这样就没有问题了,经试验这种是最方便实用的。
在此之前曾经做过多次尝试,比如在GBKString这个类里只用get时转码,set时不转同时过滤器设定iso-8859-1。这个也勉强可以用,但在Java类中使用对象的set方法,需要手工转。