mysql tinyint(1)与boolean

Mysql读取tinyint(1)数据时,如果我们没有在jdbc url里特殊指定,那么tinyint(1)的数据,会被转化为boolean类型。
jdbcResultSetImpl类中有一段代码

        switch (field.getSQLType()) {
            case Types.BIT:
                if (field.getMysqlType() == MysqlDefs.FIELD_TYPE_BIT && !field.isSingleBit()) {
                    return getObjectDeserializingIfNeeded(columnIndex);
                }
                return Boolean.valueOf(getBoolean(columnIndex));

            case Types.BOOLEAN:
                return Boolean.valueOf(getBoolean(columnIndex));

            case Types.TINYINT:
                if (!field.isUnsigned()) {
                    return Integer.valueOf(getByte(columnIndex));
                }

                return Integer.valueOf(getInt(columnIndex));
                ...

对于tinyint(1)类型的字段,读到的数据会先进入case Types.BIT代码段,之后会调用Boolean.valueOf(),也就是在这里tinyint被解析成了boolean

mysql的官方文档中有一段话

BOOL, BOOLEAN
These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true

如果想要让tinyint(1)转化为int,可以在jdbc url内指定属性tinyInt1isBitfalse

tinyInt1isBit
Should the driver treat the datatype TINYINT(1) as the BIT type (because the server silently converts BIT -> TINYINT(1) when creating tables)?
Default: true
Since version: 3.0.16

猜你喜欢

转载自blog.csdn.net/sweatott/article/details/78239786