Search code examples
javahibernatejpahibernate-mappinghibernate-annotations

Unknown integral data type


I have a database with the following specification for the ID:

code: VARCHAR(3) - this is the primary key, a String with a maximum length of 3 characters

And I am mapping the Id in the following way:

    @Id
    @GeneratedValue
    private String code;

And I am getting this error when trying to invoke session.save():

Exception in thread "main" org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String

What am I missing?

Thank you! :)


Solution

  • Using plain @GeneratedValue wont do the trick as it comes with the GenerationType.AUTO option which tells the persistence provider to decide for itself the strategy, but in case of String it cannot resolve any solution out of the box.

    Normally you would go for the uuid custom generation strategy, but that would result in strings of length=32 which is more that your column can handle.

    If you really want to avoid setting the id manually each time before save you could take advantage of the PrePersist entity listener:

    @PrePersist
    private void generateCodeIdentifier(){
        setCode(/* Generate the unique code identifier */);
    }