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

mun*_*ish 5 java spring jdbc spring-jdbc

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

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

例子:

Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, new StudentRowMapper());
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Let*_*ank 5

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

@Component
private RowMapper class...
Run Code Online (Sandbox Code Playgroud)

...

@Service
WhateverService class...

@Autowired
private SomeRowMapper theRowMapper;


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