You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java/Gradle项目中MyBatis操作SQLite自增主键插入为null问题求助

解决SQLite + MyBatis插入后主键ID返回Null的问题

核心原因

SQLite的JDBC驱动对MyBatis useGeneratedKeys 参数的支持逻辑和MySQL驱动存在差异,直接依赖@Options(useGeneratedKeys=true)无法正确获取自动生成的主键值,需要改用SQLite原生的主键获取方式。

解决方案

1. 替换@Options为@SelectKey

修改插入映射器的注解,通过SQLite原生的LAST_INSERT_ROWID()函数获取刚插入记录的主键:

@Insert({
    "INSERT INTO event(time, duration, summary_id)",
    "VALUES(#{e.time}, #{e.duration}, #{summaryId})"
})
@SelectKey(
    statement = "SELECT LAST_INSERT_ROWID()",
    keyProperty = "result.id",
    before = false,
    resultType = int.class
)
void insert(@Param("e") final Event item, @Param("summaryId") final int summaryId, @Param("result") final IdentifierResult result);
  • before=false:指定在插入语句执行完成后再查询主键
  • resultType=int.class:匹配IdentifierResult.id的类型,确保MyBatis能正确注入值

2. 升级SQLite JDBC驱动版本

确保使用最新版的SQLite JDBC驱动(如org.xerial:sqlite-jdbc),旧版本可能存在主键获取的兼容性问题。Gradle依赖配置示例:

implementation 'org.xerial:sqlite-jdbc:3.45.2.0'

3. 检查IdentifierResult的可访问性

确保IdentifierResult类的id字段有对应的setter方法,或者字段本身为可访问状态(如public修饰),否则MyBatis无法将获取到的主键值注入进去。示例实现:

public class IdentifierResult {
    private int id;

    // 必须提供setter方法
    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}

4. 确认表结构有效性

你的表结构是正确的:INTEGER PRIMARY KEY会自动关联SQLite的rowid,无需额外添加AUTOINCREMENT(该关键字仅用于限制主键不重用已删除的ID值,不影响自动生成主键的核心功能)。

验证方式

插入记录后,直接执行以下SQL确认主键和记录的对应关系:

SELECT * FROM event WHERE id = (SELECT LAST_INSERT_ROWID());

内容的提问来源于stack exchange,提问作者Catie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:43:29