spring jdbc模板自定义类型

问题描述:

在我的项目中,我使用Spring 3.0 JdbcTemplate来实现DAO类。它提供了诸如查询(...),更新(...)等方便的方法。这些方法接受对象作为绑定到查询的参数。在javadoc中,声明它是由PreparedStatement来猜测相应的SQL类型。所以当使用原语或包装时,它很简单。spring jdbc模板自定义类型

但在我的代码中,我使用特殊的类来表示id。例如UserId。它具有获取其整数值的公共方法 - getInt()。现在我必须使用

userId.getInt() 

每次我需要将UserId的实例传递给JdbcTemplate查询。如果我忘了写只是

userId 

我明明得到的SQLException,因为我的用户ID对象不能预处理语句(here are the rules to map Object type to corresponding SQL type)被消耗。但是这种类型的错误在编译期间无法被发现(因为JdbcTemplate接受Object作为参数),这使得错误的引入变得容易。

有什么办法可以避免调用.getInt(),只是将我的UserId对象传入查询?

我想你可以覆盖org.springframework.jdbc.core.JdbcTemplate.newArgPreparedStatementSetter(Object[])org.springframework.jdbc.core.ArgPreparedStatementSetter的新版本检查(在doSetValue)对象argValue是否是你的特殊UserId类型。

+0

谢谢! newArgPreparedStatementSetter确实受保护。但是这有一个问题 - ArgPreparedStatementSetter具有包保护的默认修饰符。所以我不能直接扩展它(想知道为什么春天团队不允许这样做会很方便!) –

+0

ok我最终重写了我自己的{ArgPreparedStatementSetter}版本,然后扩展{JdbcTemplate}以覆盖{newArgPreparedStatementSetter}方法 –