如何在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
相关产品推荐
相关产品推荐

