views:

1538

answers:

3

If there are 2 columns in database, eg.

code varchar(3) name nvarchar(50)

how to tell hibernate to pass varchar for searching by code?

In the hibernate mappings string is mapped to nvarchar and it produces queries like:

Select code, name From table where code=N'AAA' (instead of code='AAA')

This is very bad as it causes index scan instead of index seek operation (scanning all index nodes instead of directly going to requested one)

As code is used in millions of rows as well as in several indexes and foreign keys, changing it from varchar to nvarchar will cause performance degradation (more IO operations as nvarchar uses twice more space than varchar).

Is there any way to tell hibernate to do mapping according to database type, not to Java type?

Thanks

A: 

I think this link can help you http://blog.tremend.ro/2007/05/23/hibernate-utf-8-and-sql-server-2005/

Diego Dias
there's nothing about my question. There is explained how to extend dialect to support additional SQL types, even varchar is mapped to nvarchar
Niikola
A: 

I'm assuming you're talking about NHibernate rather than Hibernate because the latter does not use nvarchar in its default SqlServer dialect.

The way to solve your problem is to specify column type as "AnsiString" in your mapping:

<property name="Code" type="AnsiString"/>

Take a look at this post for more details.

ChssPly76
We are using Hibernate and it is sending them as nvarchar (and it's causing the biggest performance hit on our SQL box because of the index scan)
Eric Labashosky
+1  A: 

Probably you already solved this, but I had a similar problem.

I'm using jTDS JDBC driver and I solved the index scan problem by adding:

;sendStringParametersAsUnicode=false;prepareSQL=0

to the end of the jTDS connection string.

Probably it would not had solved your problem because by doing this, jTDS will only use VARCHAR (no NVARCHAR anymore).

Also, I had to disable the prepared SQL, because Hibernate is using 'like' instead of '=' when generating the queries and by using 'like' combined with a variable (SELECT ... WHERE column LIKE @var) causes an index scan (MSSQL 2000).

golimpio
;sendStringParametersAsUnicode=false solved this problem for us. We did not need to add ;prepareSQL=0 since that was working correct for us. Thx!
Atle