Skip to content
Advertisement

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

When fetching results from database through SpringJdbcTemplate, everywhere I have seen that they are passing the new object of RowMapper` every time.

Is this required? Or can we just use one object and pass it again and again?

Example:

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 reuse the row mapper instance, like this?:

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

Has this any thread safety issue?

Advertisement

Answer

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
private RowMapper class...

@Service
WhateverService class...

@Autowired
private SomeRowMapper theRowMapper;


public void doSomething() {
    Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, theRowMapper);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement