Titulum
Titulum

Reputation: 11476

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

Upvotes: 8

Views: 14759

Answers (2)

Titulum
Titulum

Reputation: 11476

Actually, it turns out that the @Column JPA annotation allows you to specify the column type (without having to use the @Type or @Nationalized annotations):

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

Upvotes: 11

Simon Martinelli
Simon Martinelli

Reputation: 36143

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

Upvotes: 14

Related Questions