MyBatis 中何时使用 jdbcType
这个 SQL 有时候这样写:select * from user where name = #{name} ,有时候可以这样写: select * from user where name = #{name,jdbcType=VARCHAR} ,到底什么时候使用 jdbcType 呢,什么时候不使用呢?
-
当传入的参数
name的值为空的时候,这个需要带上jdbcType=VARCHAR这个,其他不为空的情况下就不用带
jdbcType=VARCHAR -
如果参入的参数
name的值为空,而没有加上jdbcType这个来限定类型的话,执行的SQL会报异常:
1 | Error querying database. Cause: org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $1 |
MyBatis 的 jdbcType 和 javaType 什么时候用
如果数据库 id 字段是 int 类型,那么它的 jdbc 就是 Integer 类型。当实体类的这个映射属性 id 为 Long 类型时,如果不设置 jdbcType 和 javaType 的话,查询的结果返回给实体时就会转换错误,写了这两个 mybatis 就会帮我们转换成相应的类型,从来避免发生错误。
ofType 和 javaType 的区别
JavaType 和 ofType 都是用来指定对象类型的,但是 JavaType 是用来指定 pojo 中属性的类型,而 ofType 指定的是映射到 list 集合属性中 pojo 的类型。
pojo 类:
1 | publicclass User { |
user.xml:
1 | <resultMap type="User" id="resultUserMap"> |
Mybatis 中 jdbcType 和 javaType 以及数据库类型的对应关系
| jdbcType | javaType | mysql | oracle |
|---|---|---|---|
| CHAR | String | CHAR | CHAR |
| VARCHAR | String | VARCHAR | VARCHAR |
| LONGVARCHAR | String | VARCHAR | LONG |
| NUMERIC | java.math.BigDecimal | NUMERIC | NUMERIC/NUMBER |
| DECIMAL | java.math.BigDecimal | DECIMAL | DECIMAL |
| BIT | boolean | BIT | |
| BOOLEAN | boolean | ||
| TINYINT | byte | TINYINT | TINYINT |
| SMALLINT | short | SMALLINT | SMALLINT |
| INTEGER | int | INTEGER | INTEGER |
| BIGINT | long | BIGINT | |
| REAL | float | REAL | REAL |
| FLOAT | double | FLOAT | FLOAT |
| DOUBLE | double | DOUBLE | NUMBER |
| BINARY | byte[] | ||
| VARBINARY | byte[] | ||
| LONGVARBINARY | byte[] | ||
| DATE | java.sql.Date | DATE | DATE |
| TIME | java.sql.Time | TIME | |
| TIMESTAMP | java.sql.Timestamp | TIMESTAMP/DATETIME | TIMESTAMP |
| CLOB | Clob | CLOB | CLOB |
| BLOB | Blob | BLOB | BLOB |
| ARRAY | Array | ||
| DISTINCT | mapping of underlying type | ||
| STRUCT | Struct | ||
| REF | Ref | ||
| DATALINK | java.net.URL | ||
| NCLOB | NCLOB |
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !