我们可以使用一个RowMapper对象而不是每次创建对象来获取结果吗? [英] Can we fetch the results using one RowMapper object instead of creating objects everytime?

查看:129
本文介绍了我们可以使用一个RowMapper对象而不是每次创建对象来获取结果吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过springJdbcTemplate从db获取结果时,到处都可以看到它们每次都传递RowMapper的新对象. 这是必需的吗?或者我们可以只使用一个对象,然后一次又一次地传递它.

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.

我可以使用

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

?

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

Has this any thread safety issue?

推荐答案

为什么不仅仅创建RowMapper并让Spring管理它?应该没有理由每次都创建一个新实例.只需在由Spring管理的那一台中自动布线.只要您的映射器没有执行任何非线程安全的操作,就应该没事.

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);
}

这篇关于我们可以使用一个RowMapper对象而不是每次创建对象来获取结果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆