Sealyu

--- 博客已迁移至: http://www.sealyu.com/blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  618 随笔 :: 87 文章 :: 225 评论 :: 0 Trackbacks

I found out today that MS Sql server seems to handle Unicode in a very special way. Instead of having some support a database or table level, each Unicode column have to be created as “national”. That is be either nchar, nvarchar or ntext.

Ms SQL Server 2005 seems to go one step further by announcing future deprecation for ntext, text and image types.

From Sql Server 2005 notes:

ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.”

When working with Hibernate it seems there is no dialect to handle Unicode integration properly. You have to get down and write a custom dialect that maps to the new data types.

/**
* Unicode support in SQL Server
*
* @author icocan
*/
public class UnicodeSQLServerDialect extends SQLServerDialect {

public UnicodeSQLServerDialect() {
super();

// Use Unicode Characters
registerColumnType(Types.VARCHAR, 255, "nvarchar($l)");
registerColumnType(Types.CHAR, "nchar(1)");
registerColumnType(Types.CLOB, "nvarchar(max)");

// Microsoft SQL Server 2000 supports bigint and bit
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.BIT, "bit");
}
}
read more ...

You have to write your own SQLServerDialect class, it looks something like this:
publicclassSQLServerNativeDialectextendsSQLServerDialect{
     publicSQLServerNativeDialect(){
         super();
         registerColumnType(Types.VARCHAR,"nvarchar($l)");
         registerColumnType(Types.CLOB,"nvarchar(max)");
     }

    publicString getTypeName(int code,int length,int precision,int scale)throwsHibernateException{
        if(code !=2005){
            returnsuper.getTypeName(code, length, precision, scale);
        }else{
            return"ntext";
        }
    }
}

This class maps Hibernate's types to SQL types, so the class will map the nvarchar(max) SQL Data Type to Hibernate's CLOB data type.

The getTypeName method is used to return "ntext" when Hibernate asks about the data type with code 2005 (which looks like it's the nvarchar(max) data type).

Finally, you need to change your hibernate persistence dialect to this new SQLServerDialect class, which allows hibernate to translate data types into SQL data types.


posted on 2010-11-29 18:49 seal 阅读(677) 评论(0)  编辑  收藏 所属分类: 数据库

只有注册用户登录后才能发表评论。


网站导航: