throw CoercionException when CharacterJavaType receives a string of wrong length

Signed-off-by: Gavin King <gavin@hibernate.org>
This commit is contained in:
Gavin King 2024-10-30 12:15:04 +01:00
parent 7df56dadda
commit 920d4bce44
2 changed files with 7 additions and 7 deletions

View File

@ -36,7 +36,7 @@ public class CharacterJavaType extends AbstractClassJavaType<Character> implemen
@Override @Override
public Character fromString(CharSequence string) { public Character fromString(CharSequence string) {
if ( string.length() != 1 ) { if ( string.length() != 1 ) {
throw new HibernateException( "multiple or zero characters found parsing string" ); throw new CoercionException( "value must contain exactly one character: '" + string + "'" );
} }
return string.charAt( 0 ); return string.charAt( 0 );
} }
@ -68,12 +68,10 @@ public class CharacterJavaType extends AbstractClassJavaType<Character> implemen
return character; return character;
} }
if (value instanceof String string) { if (value instanceof String string) {
// Note that this conversion is "dangerous", if ( string.length() != 1 ) {
// since it is not invertible, and can in throw new CoercionException( "value must contain exactly one character: '" + string + "'" );
// principle result in accidental loss of data. }
// It might be better to throw if the incoming return string.charAt( 0 );
// string does not have length one.
return string.isEmpty() ? null : string.charAt( 0 );
} }
if (value instanceof Number number) { if (value instanceof Number number) {
return (char) number.shortValue(); return (char) number.shortValue();

View File

@ -7,6 +7,8 @@ package org.hibernate.type.descriptor.java;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
/** /**
* A problem converting between JDBC types and Java types.
*
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class CoercionException extends HibernateException { public class CoercionException extends HibernateException {