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

被刻印的时光 ゝ 提交于 2020-01-01 11:57:10

问题


When fetching results from db through springJdbcTemplate, everywhere I have seen that they are passing the new object of RowMapper everytime. Is this required? Or can we just use one object and pass it again and again.

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

I know this object will be garbage collected later on, but I didn't wanted to create the same object over and over again.

Can I use

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

?

Has this any thread safety issue?


回答1:


Why not just create your RowMapper and let Spring manage it? There should be no reason to create a new instance every time. Just autowire in the one managed by Spring. As long as your mapper isn't doing anything non-thread-safe, then should be just fine.

@Component
...RowMapper class...

...

@Service
...WhateverService class...

@Autowired
private RowMapperClass theRowMapper;


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



回答2:


Yes you should be able to reuse the object.

As long as your class is thread safe there is no issue. JdbcTemplate is thread safe by design



来源:https://stackoverflow.com/questions/34951402/can-we-fetch-the-results-using-one-rowmapper-object-instead-of-creating-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!