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