Mapping to varchar and nvarchar in hibernate

二次信任 提交于 2020-01-09 19:06:10

问题


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


回答1:


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).




回答2:


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.




回答3:


<type-mapping>
        <sql-type jdbc-type="NVARCHAR" hibernate-type="string" />
 </type-mapping>

Add the above code in the hibernate reveng file.




回答4:


In hibernate.properties set the property hibernate.connection.defaultNChar=false.

You can either hide your tables behind views or use nstring type. This type is available in hibernate-core 4.x. In hibernate-core 3.6.10.Final you will need to define the custom type nstring - see the comment in the url: Getting Hibernate and SQL Server to play nice with VARCHAR and NVARCHAR.



来源:https://stackoverflow.com/questions/1306774/mapping-to-varchar-and-nvarchar-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!