Swimming with the Razorfishes

Wednesday, July 27, 2005

I recently found myself needing to stick Unicode text into a table in an Oracle database built with an ASCII character set. Two things were unclear at that time: could an ASCII Oracle database hold Unicode without screwing it up; could I tell Hibernate (the underlying OR mapping tool) to treat a few columns as Unicode, treating the rest as ASCII.

It turns out that the answer to the first question is "yes." The standard NCHAR and NVARCHAR seem to work fine, even in an ASCII database. The code below solves the second problem. This is a subclass of a Hibernate Type. Using this type in the Hibernate mapping file instead of the standard String type was all that I needed.

I'm sticking this example out here in case anyone else needs to do something similar. If anyone sees any issues with the code, let me know.

public class UnicodeStringType extends org.hibernate.type.StringType

{
private static final String WEBLOGIC_NATIVE_ACCESSOR = "getVendorObj";
private Method oracleNativeStatementAccessor;


public void set(PreparedStatement st, Object value, int index) throws SQLException
{
super.set(st, value, index);

PreparedStatement nativeStatement = null;

try
{
this.oracleNativeStatementAccessor
= st.getClass().getMethod(WEBLOGIC_NATIVE_ACCESSOR, (Class[]) null);
nativeStatement = this.getNativePreparedStatement(st);
}
catch (Exception e)
{
e.printStackTrace();
throw new ApplicationException(e);
}

((OraclePreparedStatement) nativeStatement).setFormOfUse(index, OraclePreparedStatement.FORM_NCHAR);
}


/**
* Retrieve the PreparedStatemtn via WebLogic's getVendorObj method.
*/
private PreparedStatement getNativePreparedStatement(PreparedStatement con)
throws IllegalAccessException, InvocationTargetException
{
return (PreparedStatement) this.oracleNativeStatementAccessor.invoke(con, (Object[]) null);
}
}

1 Comments:

  • Thankyou for sharing, i almost used that, but unfortunatelly i don't use weblogic server etc.

    But, i found another way to acomplish what you did.

    Define -Doracle.jdbc.defaultNChar=true while starting your tomcat or whatever thing, and that obsoletes your need to setFormOfUse().

    on the flipside of the coin, it counts as you had setForOfUse to this NCHAR for every character field. i guess it would be somewhat performance hit, but in case you would end up using nvarchar in most places anyhow, then it would not matter.

    By Anonymous Anonymous, at 3:46 AM  

Post a Comment

<< Home