通过springJdbcTemplate从db获取结果时,到处都可以看到它们每次都传递RowMapper的新对象。这是必需的吗?或者我们可以只使用一个对象并一次又一次地传递它。
Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, new StudentRowMapper());
我知道以后会对该对象进行垃圾回收,但是我不想一遍又一遍地创建相同的对象。
我可以用吗
Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, this.studentMapper);
?
这有线程安全问题吗?
为什么不只创建RowMapper并让Spring管理它呢?每次都没有理由创建新实例。只需自动连接Spring管理的那一台。只要您的映射器没有执行任何非线程安全的操作,那就应该没问题。
@Component
...RowMapper class...
...
@Service
...WhateverService class...
@Autowired
private RowMapperClass theRowMapper;
public void doSomething() {
Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, theRowMapper);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句