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

如何在JDBI中注册可处理多种参数类型的ArgumentFactory?

在JDBI中注册可处理多种参数类型的ArgumentFactory

答案是可以的。

官方提供的AbstractArgumentFactory只是简化单一参数类型处理的抽象实现,但底层的ArgumentFactory接口本身并没有限制工厂能处理的参数类型数量。你只需要直接实现ArgumentFactory接口,而非继承AbstractArgumentFactory,就能在逻辑中处理多种类型。

实现思路

  • 在accepts方法中,判断传入的参数类型是否属于你要处理的多种类型之一;
  • 在build方法中,根据参数的实际类型,生成对应的Argument实例。

示例代码

public class MultiTypeArgumentFactory implements ArgumentFactory {
    @Override
    public boolean accepts(Class<?> type, Object value, StatementContext ctx) {
        // 同时支持LocalDate和LocalDateTime类型
        return type == LocalDate.class || type == LocalDateTime.class;
    }

    @Override
    public Argument build(Class<?> type, Object value, StatementContext ctx) {
        if (value instanceof LocalDate date) {
            return (pos, stmt, ctx) -> stmt.setDate(pos, Date.valueOf(date));
        } else if (value instanceof LocalDateTime dt) {
            return (pos, stmt, ctx) -> stmt.setTimestamp(pos, Timestamp.valueOf(dt));
        }
        throw new IllegalArgumentException("不支持的参数类型: " + type);
    }
}

注册方式

和注册普通的ArgumentFactory一样,直接通过Jdbi实例注册即可:

Jdbi jdbi = Jdbi.create("jdbc:h2:mem:test");
jdbi.registerArgumentFactory(new MultiTypeArgumentFactory());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:35:14