Hibernate连接Oracle数据库乱码问题

Hibernate连接Oracle数据库乱码问题

文章分类:Java编程

最近做了个项目,用的框架式Struts+Spring+Hibernate框架的,以前用这个框架连接的数据库都是GBK编码集的,这次连接的是Oracle AMERICAN_AMERICA.US7ASCII编码的,这样就导致项目运行后全是乱码,郁闷了很久,要是每个都自己写转码,实在是太累了,也很烦,所以就考虑是不是在Hibernate里通过什么方法使汉字编码正常。
经过多次尝试、找高手请教和网上的查找最后发现一种比较方便实用的方法:


首先定义一个GBKString替换默认的类型,在映射文件中使用该类型做为TYPE
例如:

Java代码

  1. <property name="battrancode" column="battrancode" type="String" />  

<property name="battrancode" column="battrancode" type="String" />


替换为:

Java代码

  1. <property name="battrancode" column="battrancode" type="com.nl.tsp.dao.GBKString" />  

<property name="battrancode" column="battrancode" type="com.nl.tsp.dao.GBKString" />

 

 

Java代码

  1.     
  2. GBKString.java    
  3. Java代码    
  4. package com.nl.tsp.dao;      
  5.      
  6. import java.io.Serializable;      
  7. import java.io.UnsupportedEncodingException;      
  8. import java.sql.PreparedStatement;      
  9. import java.sql.ResultSet;      
  10. import java.sql.SQLException;      
  11.      
  12. import oracle.jdbc.driver.OracleTypes;      
  13.      
  14. import org.apache.commons.lang.builder.HashCodeBuilder;      
  15. import org.hibernate.HibernateException;      
  16. import org.hibernate.usertype.UserType;      
  17.      
  18. /**    
  19.  * @description    
  20.  * @author Jason Tseng    
  21.  *     
  22.  */     
  23. public class GBKString implements UserType {      
  24.      
  25.     public GBKString() {      
  26.         super();      
  27.     }      
  28.      
  29.     public int[] sqlTypes() {      
  30.         return new int[] { OracleTypes.VARCHAR };      
  31.     }      
  32.      
  33.     public Class returnedClass() {      
  34.         return String.class;      
  35.     }      
  36.      
  37.     public boolean equals(Object x, Object y) throws HibernateException {      
  38.         return (x == y) || (x != null && y != null && (x.equals(y)));      
  39.     }      
  40.      
  41.     public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException,      
  42.             SQLException {      
  43.         String val = rs.getString(names[0]);      
  44.         if (null == val) {      
  45.             return null;      
  46.         } else {      
  47.             try {      
  48.                 val = new String(val.getBytes("iso-8859-1"), "GBK");      
  49.             } catch (UnsupportedEncodingException e) {      
  50.                 throw new HibernateException(e.getMessage());      
  51.             }      
  52.             return val;      
  53.         }      
  54.     }      
  55.      
  56.     public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException,      
  57.             SQLException {      
  58.         if (value == null) {      
  59.             st.setNull(index, OracleTypes.VARCHAR);      
  60.         } else {      
  61.             String val = (String)value;      
  62.             try {      
  63.                 val = new String(val.getBytes("GBK"), "iso-8859-1");      
  64.             } catch (UnsupportedEncodingException e) {      
  65.                 throw new HibernateException(e.getMessage());      
  66.             }      
  67.             st.setObject(index, val, OracleTypes.VARCHAR);      
  68.         }      
  69.     }      
  70.      
  71.     public Object deepCopy(Object value) throws HibernateException {      
  72.         if (value == null)      
  73.             return null;      
  74.         return new String((String) value);      
  75.     }      
  76.      
  77.     public boolean isMutable() {      
  78.         return false;      
  79.     }      
  80.      
  81.     public Object assemble(Serializable arg0, Object arg1) throws HibernateException {      
  82.         // TODO Auto-generated method stub      
  83.         return null;      
  84.     }      
  85.      
  86.     public Serializable disassemble(Object arg0) throws HibernateException {      
  87.         // TODO Auto-generated method stub      
  88.         return null;      
  89.     }      
  90.      
  91.     public int hashCode(Object arg0) throws HibernateException {      
  92.         return HashCodeBuilder.reflectionHashCode(this);      
  93.     }      
  94.      
  95.     public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {      
  96.         // TODO Auto-generated method stub      
  97.         return null;      
  98.     }      
  99. }    

 

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方法,需要手工转。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Hibernate是一个Java持久化框架,可以连接MySQL数据库连接MySQL数据库需要以下步骤: 1. 在项目中添加MySQL驱动程序的依赖项。 2. 在Hibernate配置文件中配置MySQL数据库连接信息,包括数据库URL、用户名、密码等。 3. 在Java代码中使用Hibernate API来连接MySQL数据库,执行SQL语句或者操作数据库。 例如,以下是Hibernate配置文件中连接MySQL数据库的示例: ``` <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> </session-factory> </hibernate-configuration> ``` 其中,`hibernate.connection.driver_class`指定MySQL驱动程序的类名,`hibernate.connection.url`指定数据库的URL,`hibernate.connection.username`和`hibernate.connection.password`指定数据库的用户名和密码,`hibernate.dialect`指定Hibernate使用的MySQL方言,`hibernate.show_sql`指定是否在控制台输出SQL语句。 连接MySQL数据库后,可以使用Hibernate API来操作数据库,例如: ``` Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); // 执行SQL语句或者操作数据库 ... tx.commit(); session.close(); ``` 其中,`sessionFactory`是Hibernate的会话工厂,`session`是Hibernate的会话对象,`tx`是Hibernate的事务对象。在事务中执行SQL语句或者操作数据库,最后提交事务并关闭会话。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hjay0715

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值