我们可以使用一个 RowMapper 对象而不是每次都创建对象来获取结果吗?

Can we fetch the results using one RowMapper object instead of creating objects everytime?

每次通过SpringJdbcTemplate, everywhere I have seen that they are passing the new object of RowMapper`从数据库中获取结果时。

这是必需的吗?或者我们可以只使用一个对象并一次又一次地传递它吗?

示例:

Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, new StudentRowMapper());

我知道这个对象稍后会被垃圾回收,但我不想一遍又一遍地创建相同的对象。

我可以像这样重用行映射器实例吗?:

Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, this.studentMapper);

这有任何线程安全问题吗?

是的,您应该可以重复使用该对象。

只要您的 class 是线程安全的,就没有问题。 JdbcTemplate 在设计上是线程安全的

为什么不直接创建您的 RowMapper 并让 Spring 管理它呢?没有理由每次都创建一个新实例。只需在 Spring 管理的那个中自动装配。只要您的映射器不做任何事情 non-thread-safe,就应该没问题。

@Component
private RowMapper class...

...

@Service
WhateverService class...

@Autowired
private SomeRowMapper theRowMapper;


public void doSomething() {
    Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, theRowMapper);
}