基于spring的NamedParameterJdbcTemplate操作数据库
- 首先在 resources 文件夹下添加数据库配置文件jdbc.properties 配置常用的数据库信息
consult.jdbc.driverClassName=com.mysql.jdbc.Driver
consult.jdbc.url=jdbc:mysql://xxxxxxxx:3307/consult_summer?useUnicode=true&characterEncoding=utf-8&tinyInt1isBit=false
consult.jdbc.username=root
consult.jdbc.password=123456 - 将配置文件添加到集中加载的配置文件中,即在applicationContext.xml文件中添加如下内容
<!-- 加载资源文件,所有的资源文件都集中加载,不要分散到其他spring配置文件中,否则会找不到 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean> - 然后在 applicationContext.xml 文件中增加如下内容,用来对NamedParameterJdbcTemplate的bean 的引入
<bean id="consultDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${consult.jdbc.driverClassName}" />
<property name="url" value="${consult.jdbc.url}" />
<property name="username" value="${consult.jdbc.username}" />
<property name="password" value="${consult.jdbc.password}" />
</bean> <bean id="consultTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="consultDataSource" />
</bean> - 上面配置完成,下面开始写一个测试类Testdemo来操作数据库(以查询为例)
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml") public class Testdemo { private static final Log log = LogFactory.getLog(TestJdbc.class); // 引入注解
@Resource
protected NamedParameterJdbcTemplate consultTemplate;
@Test
public void test() throws Exception{ StringBuffer sql = new StringBuffer("SELECT * FROM " + "order_info_ext_96"
+ " WHERE 1=1 ");
StringBuffer sqlToLog = new StringBuffer(sql);
Map<String,Object> para=new HashMap<String, Object>();
para.put("order_info_id","tm2zd0ww21190111030136219");
Set<String> columnNames = para.keySet();
for (String columnName : columnNames) {
sql.append(" AND " + columnName + "=:" + columnName);
sqlToLog.append(" AND " + columnName + "='"
+ para.get(columnName) + "'");
}
List<Map<String, Object>> select_result=consultTemplate.queryForList(sql.toString(),para);
log.info(select_result); //打印查询结果 }
} -
运行即可查看结果,运行完成即可将方法改成参数式的,以供调用