使用spring的jdbcTemplate时,需要的配置文件

来源:互联网 发布:原油eia数据最新消息 编辑:程序博客网 时间:2024/06/15 18:10

过程是这样的,在阅读代码Fwpjdaoimpl.java文件时,其中用到jdbcTemplate与数据库交互,但是具体怎么用,以及怎么配置当时还不是太了解,查阅一些资料后,懂了一些

代码如下:

@Override
    public int getAllCountByZjhm(String zjhm) {
        String sql = "select count(1) from (" + pjsql + ") t ";
        return getJdbcTemplate().queryForInt(sql, zjhm, zjhm, zjhm);
    }

    @Override
    public int getAllYPJCountByZjhm(String zjhm) {
        String sql = "select count(1) from (" + pjsql + ") t where NSfpj = " + FwpjConstant.SFPJ_YPJ + " or NSfpj = " + FwpjConstant.PJZT_YPJ;
        return getJdbcTemplate().queryForInt(sql, zjhm, zjhm, zjhm);
    }

光有代码还不行,还需要进行配置:

首先在该模块包下建立一个fepj-dao.xml配置文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


<bean id="fwpjDao" class="com.thunisoft.susong51.fwpj.dao.impl.FwpjDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>


<bean id="ajpjDao" class="com.thunisoft.susong51.fwpj.dao.impl.AjpjDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>


</beans>

该配置文件的作用是将jdbcTemplate注入到fwpjdao中

第二步:

需要在applicationContext.xml文件中配置dataSource,并将dataSource注入到jdbcTemplate中,代码如下:

<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>  //这里为读取配置文件的路径
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>${dataSource.driverClass}</value>
</property>
<property name="url">
<value>${dataSource.jdbcUrl}</value>
</property>
<property name="username">
<value>${dataSource.user}</value>
</property>
<property name="password">
<value>${dataSource.password}</value>
</property>
<property name="maxActive">
<value>${dbcp.maxActive}</value>
</property>
<property name="initialSize">
<value>${dbcp.initialSize}</value>
</property>
<property name="maxWait">
<value>${dbcp.maxWait}</value>
</property>
<property name="minIdle">
<value>${dbcp.minIdle}</value>
</property>
<property name="timeBetweenEvictionRunsMillis">
<value>${dbcp.timeBetweenEvictionRunsMillis}</value>
</property>
<property name="minEvictableIdleTimeMillis">
<value>${dbcp.minEvictableIdleTimeMillis}</value>
</property>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>

这样,整个配置就完成了,可以使用了