通过Mybatis插入Java boolean到PostgreSQL boolean失败求助
MyBatis插入Java boolean到PostgreSQL boolean字段报错,提示表达式为integer类型
尝试通过MyBatis将Java的boolean类型插入PostgreSQL的boolean字段时失败,报错提示目标列是boolean类型,但传入的表达式是integer类型,明明所有相关类型都是boolean,为什么会出现这个问题?
错误信息
org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: org.postgresql.util.PSQLException: ERROR: column columnname1 is of type boolean but expression is of type integer Hint: You will need to rewrite or cast the expression. Position: 880 Location: File: parse_target.c, Routine: transformAssignedExpr, Line: 586 Server SQLState: 42804 ### The error may exist in URL [jar:file:/path1/jarname1.jar!/BOOT-INF/lib/jarname2.jar!/config/mybatis/mappername1.xml] ### The error may involve com.pathname1.pathname2.repository.mappername1.insert-Inline ### The error occurred while setting parameters ### SQL: insert into tablename1( columnname1, columnname2, ...) values ( ?, ?,... )
相关代码
POJO类
package com.pathname1.pathname2.db.data.mybatis; import ... public class pojoname1{ private ... private boolean pojofield1= false; private ... ... public boolean ispojofield1() { return pojofield1; } public void setpojofield1(boolean pojofield1) { this.pojofield1= pojofield1; } ... }
Mapper映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.pathname1.pathname2.repository.mappername1"> ... <insert id="insert" parameterType="com.pathname1.pathname2.db.data.mybatis.pojoname1" useGeneratedKeys="true" keyProperty="id" keyColumn="id"> insert into tablename1( columnname1, ... ) values ( #{pojofield1,jdbcType=BOOLEAN,javaType=boolean}, ... ) </insert> ... </mapper>
版本信息
- Java 8
- mybatis-spring 2.1.2
- mybatis 3.5.16
- postgresql 42.7.3
解决思路
- 调整JDBC连接参数
在PostgreSQL的JDBC URL中添加stringtype=unspecified参数,强制驱动按正确的类型映射处理:
jdbc:postgresql://localhost:5432/your_db?stringtype=unspecified
检查POJO属性的映射规则
虽然boolean类型的getter用isXXX符合规范,但MyBatis的自动映射偶尔会出现识别偏差。可以尝试将getter改为getPojofield1()(首字母大写),或者在Mapper的参数中明确指定属性映射。排查MyBatis全局类型配置
检查mybatis-config.xml中是否存在自定义的类型处理器或类型别名,若有自定义BooleanTypeHandler,确认其是否正确将Java boolean映射为JDBC BOOLEAN类型,而非INTEGER。显式指定类型处理器
在Mapper的参数中直接指定MyBatis自带的类型处理器:
#{pojofield1,typeHandler=org.apache.ibatis.type.BooleanTypeHandler}
- 确认数据库字段类型
通过psql命令\d tablename1再次确认columnname1的字段类型确实是boolean,避免因表结构定义错误导致的问题。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

