This answer recommends two options when mapping a VARCHAR type to UUID class:
@Id @GeneratedValue
@JdbcTypeCode(Types.VARCHAR)
private UUID id;
and:
@Id @GeneratedValue
@JdbcType(VarcharJdbcType.class)
private UUID id;
What is the difference between the @JdbcTypeCode
and @JdbcType
annotations?
I read the javadoc (1, 2) for both annotations but could not figure out the difference from it. I'm aware that both of them are used to map between database type and Java types, however I would like to know in which scenario one should be used versus the other.
I read the javadoc
Good. In this case, however, the JavaDocs are a little perfunctory when taken by themselves. They should be understood in the context of Hibernate's prose documentation. In particular, its model for mapping "basic" types is relevant. That explains that Hibernate maintains three (!) distinct senses of the type of a persistent Java property that corresponds to a single column: a Hibernate type, which corresponds to a combination of a Java type representing Java-side characteristics and a JDBC type representing the characteristics of corresponding JDBC objects.
I'm aware that both of them are used to map between database type and Java types
Not exactly. The @JdbcType
annotation explicitly associates a specific JdbcType
implementation with a persistent property. The @JdbcTypeCode
annotation explicitly associates an integer code representing a JdbcType
implementation. Both options are specifically about the JDBC side of the mapping.
The Java side of the mapping is separate. It can in most cases be determined implicitly from the Java data type of the applicable property of the Java entity class, but it can also be specified explicitly via a @JavaType
annotation.
I would like to know in which scenario one should be used versus the other.
One is as good as the other when you can express what you want both ways. @JdbcType
is needed when there is no JDBC type code for what you want. In particular, @JdbcType
allows you to specify a custom JdbcType
implementation class, though it's uncommon to need to do so. You can get a JDBC type code (several, actually) from a JDBCType
, so the latter is more general.