据我所知,DataSource和JdbcTemplates都是threadsafe,因此您可以配置单个JdbcTemplate实例,然后安全地将此共享引用注入多个DAO(或存储库)。另外,DataSource应该是singleton,因为它管理连接池。
官方的Spring文档JdbcTemplate最佳实践解释了备选方案(手册的节选用斜体字表示,我的注释放在方括号内:
new JdbcTemplate(dataSource)然而,后面的一份说明不鼓励刚才提出的所有备选办法:
一旦配置完毕,JdbcTemplate实例就是线程安全。如果应用程序访问多个数据库(这需要多个JdbcTemplate,随后需要多个不同配置的JdbcTemplates ),则可能需要多个JdbcTemplates实例。
换句话说,刚才提供的所有选项都将导致多个JdbcTemplate实例(每个DAO一个),就在docs说在处理单个数据库时这是不必要的。
我要做的是直接将JdbcTemplate注入需要它的各个do,所以我的问题是,这样做可以吗?而且,您也认为Spring参考文档是自相矛盾的吗?还是我的误会?
发布于 2012-02-27 07:45:10
海事组织,向您的(多个)DAO注入JdbcTemplate没有问题。当需要运行db查询时,模板用于将DAO“连接”到物理资源(db连接)。因此,如果SessionFactory和TransactionManager配置得当,您就不会遇到并发问题-- Spring管理您使用持久层所需的bean的生命周期。使用模板的优点是:
发布于 2014-07-24 03:54:59
因此,应该有两种情况:
我们不改变DAO中的JdbcTemplate属性,我们可以定义如下:
<bean id="tlmJDBCTemplate" class="org.springframework.jdbc.core.JdbcTemplate" <property name="dataSource" ref="plmTlmDataSource"/>
</bean>注意:大多数时候我们不会更改JdbcTemplate属性,因为它是不必要的。
我们在DAO中改变JdbcTemplate属性,我们应该扩展JdbcDaoSupport。
State:
• fetchSize: If this variable is set to a non-zero value, it will be used for setting the fetchSize property on statements used for query processing(JDBC Driver default)
• maxRows: If this variable is set to a non-zero value, it will be used for setting the maxRows property on statements used for query processing(JDBC Driver default)
• queryTimeout: If this variable is set to a non-zero value, it will be used for setting the queryTimeout property on statements used for query processing.(JDBC Driver default)
• skipResultsProcessing: If this variable is set to true then all results checking will be bypassed for any callable statement processing. This can be used to avoid a bug in some older Oracle JDBC drivers like 10.1.0.2.(false)
• skipUndeclaredResults: If this variable is set to true then all results from a stored procedure call that don't have a corresponding SqlOutParameter declaration will be bypassed. All other results processing will be take place unless the variable {@code skipResultsProcessing} is set to {@code true}(false)
• resultsMapCaseInsensitive: If this variable is set to true then execution of a CallableStatement will return the results in a Map that uses case insensitive names for the parameters if Commons Collections is available on the classpath.(false)摘要:我不认为春天给导游的练习是最好的。
发布于 2020-07-07 03:03:16
这么多年之后,再看到这个问题,我想我们可以先用单例创建"Jdbc模板“,然后注入到DAO,所以它只是模板的一个实例。
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>然后,您可以将模板注入DAO或DAO扩展JdbcDaoSupport。
public final void setJdbcTemplate(JdbcTemplate jdbcTemplate)
{
this.jdbcTemplate = jdbcTemplate;
initTemplateConfig();
}https://stackoverflow.com/questions/9460507
复制相似问题