MSSQL - JPA - Character encoding for Special characters - appending 'N' nativeQuery

柔情痞子 提交于 2019-12-02 18:19:02

问题


I'm using Spring 4.3.1 with JPA 2.0 and connected to MSSQL. I'm using JpaRepository's save method to insert and update data. One of the fields has nvarchar which can contain special characters like Latin, Chinese.

Also, I have set below JPA properties in applicationContext-hibernate.xml.

            <prop key="hibernate.connection.CharSet">UTF-8</prop>
            <prop key="hibernate.connection.useUnicode">true</prop>
            <prop key="hibernate.connection.characterEncoding">UTF-8</prop>

When I save the data, all the special characters are saved as question marks(??). The solution suggested was to append 'N'in front of the update query to keep the special characters inserted. However, I don't see anywhere how to append 'N' in JpaRepository's save method. Any suggestions?


回答1:


Declare field as byte[] array as below.

@Column(name="[colName]", columnDefinition = "nvarchar", length=4000)
    private byte[] colName;

and while mapping you have to convert byte[] to String using UTF-16 would do the trick as below. From DB (mapping):

byte[] eCodeData = dbData.getColName();
            if(eCodeData != null){
                uiData.setColName(new String(eCodeData, StandardCharsets.UTF_16));
            }

to DB:

String eCodeData = uiData.getColName();
        if(eCodeData != null){
            dbData.setColName(eCodeData.getBytes(StandardCharsets.UTF_16)); 
        }

This is it. This will do the magic.




回答2:


Actually don't have to define byte[] array for the field but

@Column(columnDefinition = "nvarchar(255)")
private String colName;

That's enough.



来源:https://stackoverflow.com/questions/48085062/mssql-jpa-character-encoding-for-special-characters-appending-n-nativequ

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