Skip to content

Commit

Permalink
[hibernate#929] Refactor id generation for MySQL
Browse files Browse the repository at this point in the history
MySQL always returns an id of type Long.
This commit changes an hack that was affecting all dbs
and preventing H2 to read identity id of type Integer or Short
  • Loading branch information
DavideD committed Jun 22, 2022
1 parent 137673b commit bff1835
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ public interface Log extends BasicLogger {
@Message(id = 34, value = "The database returned no natively generated identity value")
HibernateException noNativelyGeneratedValueReturned();

@Message(id = 35, value = "The database can only generate identifiers of type Long")
HibernateException nativelyGeneratedValueMustBeLong();
@Message(id = 35, value = "The database can only generate identifiers of type Long: the id %1$d cannot be cast to %2$s ")
HibernateException nativelyGeneratedValueMustBeLong(Long id, @FormatWith(ClassFormatter.class) Class<?> idClass);

@Message(id = 356, value = "Wrong entity type!")
HibernateException wrongEntityType();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -393,11 +393,6 @@ default CompletionStage<Serializable> insertReactive(
} );

Class<?> idClass = delegate().getIdentifierType().getReturnedClass();
if ( idClass.equals(Integer.class) || idClass.equals(Short.class) ) {
// since on MySQL we can only retrieve Long values, adjust to Long
// id will be cast back to the right type by castToIdentifierType()
idClass = Long.class;
}
return getReactiveConnection( session )
//Note: in ORM core there are other ways to fetch the generated identity:
// getGeneratedKeys(), or an extra round select statement. But we
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,10 +309,19 @@ public CompletionStage<Void> close() {
private static <T> T getLastInsertedId(RowSet<Row> rows, Class<T> idClass, String idColumnName) {
final Long mySqlId = rows.property( MYSQL_LAST_INSERTED_ID );
if ( mySqlId != null ) {
// MySQL will return a Long for any of these types
if ( Long.class.equals( idClass ) ) {
return (T) mySqlId;
}
throw LOG.nativelyGeneratedValueMustBeLong();
if ( Integer.class.equals( idClass )
&& mySqlId <= Integer.MAX_VALUE ) {
return (T) mySqlId;
}
if ( Short.class.equals( idClass )
&& mySqlId <= Short.MAX_VALUE) {
return (T) mySqlId;
}
throw LOG.nativelyGeneratedValueMustBeLong( mySqlId, idClass );
}
final Row oracleKeys = rows.property( ORACLE_GENERATED_KEYS );
if ( oracleKeys != null ) {
Expand Down

0 comments on commit bff1835

Please sign in to comment.