版本:org.hibernate:hibernate-core:5.4.3.Final
源码:org.hibernate.type.descriptor.sql.JdbcTypeJavaClassMappings
JDBC 类型映射方法
/**
* For the given Java type, determine the JDBC recommended JDBC type.
*
* This includes the mappings defined in <i>TABLE B-2 - Java Types Mapped to JDBC Types</i> as well as some additional "common sense" mappings for things like BigDecimal, BigInteger, etc.
*/
public int determineJdbcTypeCodeForJavaClass(Class cls) {
Integer typeCode = javaClassToJdbcTypeCodeMap.get(cls);
if (typeCode != null) {
return typeCode;
}
int specialCode = cls.hashCode();
log.debug("JDBC type code mapping not known for class [" + cls.getName() + "]; using custom code [" + specialCode + "]");
return specialCode;
}
JDBC 类型映射表
private static ConcurrentHashMap<Class, Integer> buildJavaClassToJdbcTypeCodeMappings() {
final ConcurrentHashMap<Class, Integer> workMap = new ConcurrentHashMap<>();
// these mappings are the ones outlined specifically in the spec
workMap.put(String.class, Types.VARCHAR);
workMap.put(BigDecimal.class, Types.NUMERIC);
workMap.put(BigInteger.class, Types.NUMERIC);
workMap.put(Boolean.class, Types.BIT);
workMap.put(Short.class, Types.SMALLINT);
workMap.put(Integer.class, Types.INTEGER);
workMap.put(Long.class, Types.BIGINT);
workMap.put(Float.class, Types.REAL);
workMap.put(Double.class, Types.DOUBLE);
workMap.put(byte[].class, Types.LONGVARBINARY);
workMap.put(java.sql.Date.class, Types.DATE);
workMap.put(Time.class, Types.TIME);
workMap.put(Timestamp.class, Types.TIMESTAMP);
workMap.put(Blob.class, Types.BLOB);
workMap.put(Clob.class, Types.CLOB);
workMap.put(Array.class, Types.ARRAY);
workMap.put(Struct.class, Types.STRUCT);
workMap.put(Ref.class, Types.REF);
workMap.put(Class.class, Types.JAVA_OBJECT);
workMap.put(RowId.class, Types.ROWID);
workMap.put(SQLXML.class, Types.SQLXML);
// additional "common sense" registrations
workMap.put(Character.class, Types.CHAR);
workMap.put(char[].class, Types.VARCHAR);
workMap.put(Character[].class, Types.VARCHAR);
workMap.put(Byte[].class, Types.LONGVARBINARY);
workMap.put(java.util.Date.class, Types.TIMESTAMP);
workMap.put(Calendar.class, Types.TIMESTAMP);
return workMap;
}
可支持的最小 Number 转换
如String
转换Number
时,可支持的最小类型转换为AttributeConverter<String, Short>
:
import javax.persistence.AttributeConverter;
/**
* Converter - 字符串转换数字
*/
public class StringToNumberConverter implements AttributeConverter<String, Short> {
@Override
public Short convertToDatabaseColumn(String attribute) {
return attribute != null ? Short.valueOf(attribute) : null;
}
@Override
public String convertToEntityAttribute(Short dbData) {
return dbData != null ? dbData.toString() : null;
}
}
(完)