Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot & Hibernate: NVARCHAR column type without @Type annotation

I have a table in my database for my Customer entity. This table contains some columns that are of type NVARCHAR (this is a requirement, I can not change it), but Hibernate is not able to map this column type to the correct property in my Entity without using the @Type annotation, it's complaining that it expectd a column with type VARCHAR instead of NVARCHAR:

@Entity
public class Customer {
  // ...

  @Column(name = "first_name", nullable = false)
  @Type(type="org.hibernate.type.StringNVarcharType")
  private String firstName;

  // ...
}

Is there any way to configure hibernate to be able to map to the NVARCHAR type without using the @Type annotation, that is conform to the JPA specification?

Spring Boot version: 2.1.12.RELEASE
Hibernate version: 5.3.15.Final
Hibernate dialect: org.hibernate.dialect.SQLServer2012Dialect

like image 990
Titulum Avatar asked Dec 23 '22 18:12

Titulum


1 Answers

The recommended way would be to use the @Nationalized annotation:

@Entity
public class Customer {
  // ...

  @Column(name = "first_name", nullable = false)
  @Nationalized 
  private String firstName;

  // ...
}

But you could also set this as default:

If your application and database use nationalization, you may instead want to enable nationalized character data as the default.

You can do this via the hibernate.use_nationalized_character_data setting or by calling MetadataBuilder#enableGlobalNationalizedCharacterDataSupport during bootstrap.

In application.properties you can set:

spring.jpa.properties.hibernate.use_nationalized_character_data =true

Read more about that in the Hibernate docs https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#basic-nationalized

like image 168
Simon Martinelli Avatar answered Jan 14 '23 06:01

Simon Martinelli