How can Hibernate map the SQL data-type nvarchar(max)?

后端 未结 4 1174
我在风中等你
我在风中等你 2020-12-14 10:50

I have a column in my SQL-2005 database that used to be a varchar(max), but it has been changed to an nvarchar(max).

相关标签:
4条回答
  • 2020-12-14 11:25

    Found the answer at Tremend Tech Blog. You have to write your own SQLServerDialect class, it looks something like this:

    public class SQLServerNativeDialect extends SQLServerDialect {
         public SQLServerNativeDialect() {
             super();
             registerColumnType(Types.VARCHAR, "nvarchar($l)");
             registerColumnType(Types.CLOB, "nvarchar(max)");
         }
    
        public String getTypeName(int code, int length, int precision, int scale) throws HibernateException {
            if(code != 2005) {
                return super.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.

    0 讨论(0)
  • 2020-12-14 11:37

    I think it is registerColumnType(Types.VARCHAR, "nvarchar($l)"); // l like _l_ength, not 1.

    0 讨论(0)
  • 2020-12-14 11:43

    What worked for me is to put the actual column definition in a @Column annotation:

        @Column(name="requestXml", columnDefinition = "ntext")
    private String request;
    
    0 讨论(0)
  • 2020-12-14 11:44

    It can be fixed by @Nationalized annotation from hibernate, that marks a character data type like a nationalized variant (NVARCHAR, NCHAR, NCLOB, etc).

    0 讨论(0)
提交回复
热议问题