8

I have following entity:

@RooEntity
Class X {
    @NotNull
    private Locale locale;
}

Is it possible to store toString() representation of Locale object in database and when retrieving I can still get Locale object?

Can I use @Basic annotation here?

skaffman
  • 398,947
  • 96
  • 818
  • 769
hrishikeshp19
  • 8,838
  • 26
  • 78
  • 141

3 Answers3

10

Yes, it can be stored without any additional configuration. Hibernate has built-in basic type LocalType that converts java.util.Locale to jdbc VARCHAR type and vice versa.

Example:

...
import java.util.Locale;


@Entity
@Table(name = "user")
public class User {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;     

   @Basic(optional = false)
   private Locale locale;
    
   // getters and setters

}

SQL (tested on MySQL):

create table user
(
  id                bigint auto_increment primary key,
  locale            varchar(5)   not null
);

Result: data stored in Java locale format: "en_US"

Alex
  • 1,986
  • 22
  • 23
7

And also you can use Attribute Converter

@RooEntity
Class X {
@Column(name = "locale")
    @Convert(converter = LocaleConverter.class)
    private Locale locale;
...
}

Converter:

 public class LocaleConverter  implements AttributeConverter<Locale, String> {

    @Override
    public String convertToDatabaseColumn(Locale locale) {
        if (locale != null) {
            return locale.toLanguageTag();
        }
        return null;
    }

    @Override
    public Locale convertToEntityAttribute(String languageTag) {
        if (languageTag != null && !languageTag.isEmpty()) {
            return Locale.forLanguageTag(languageTag);
        }
        return null;
    }
  }
Virgorn
  • 151
  • 1
  • 6
4

You can persist the localeString (or language) to the DB and recreate the Locale object after you fetch your entity.

As easy as this:

@RooEntity
Class X {
    @NotNull
    @Basic
    private String localeString;



    ....
   public Locale getLocaleFromString() {
        return new Locale(localeString);
   }
}
WeMakeSoftware
  • 9,039
  • 5
  • 34
  • 52