第四章jdbcTemplate知识点
第一步先配置数据源并测试
测试
@Test public void Test02() { ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); Object obj = ioc.getBean("comboPooledDataSource"); System.out.println(obj); }
配置文件
<context:property-placeholder location="db.properties"/> <!-- #{}spring的表达式语言 --> <!-- ${}取出配置文件中的值 --> <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> <property name="jdbcUrl" value="${jdbc.jdbcUrl"/> <property name="driverClass" value="${jdbc.driverClass}"/> </bean>
导入spring数据库模块
最基础的用自己new一个jdbcTemplate
@Test public void Test02() throws SQLException { ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dsource = (DataSource) ioc.getBean("comboPooledDataSource"); Connection con = dsource.getConnection(); con.close(); } @Test public void Test03() throws SQLException { ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dsource = (DataSource) ioc.getBean("comboPooledDataSource"); new JdbcTemplate(dsource); }
也可以由spring配置注入
<context:property-placeholder location="db.properties"/> <!-- #{}spring的表达式语言 --> <!-- ${}取出配置文件中的值 --> <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/> <property name="driverClass" value="${jdbc.driverClass}"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="comboPooledDataSource"></property> <!-- <constructor-arg name="dataSource" ref="comboPooledDataSource"></constructor-arg> --> </bean> System.out.println(ioc.getBean("jdbcTemplate"));
使用jdbcTemplate来更新表
@Test public void Test03() throws SQLException { ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dsource = (DataSource) ioc.getBean("comboPooledDataSource"); JdbcTemplate jdbcTemplate = (JdbcTemplate) ioc.getBean("jdbcTemplate"); String sql = "update iteminfo set item_name = ? Where item_id = ?"; int res = jdbcTemplate.update(sql,new Object[] {"100","1"}); System.out.println(res); }
- 批量操作
List<Object[]> args ;
List多长代表执行多少遍
Object[] ->每次执行要用的参数
实验四
javabean需要和数据库中字段名一致,否则无法完成封装 sql可以其别名
jdbcTemplate.query 大部分返回List (SELECT)
jdbcTemplate.queryForObject 返回一个对象 RowMapper 下的BeanPropertyRowMapper <>(Student.class)来实现映射 查不到会报错 可以采用try catch来解决
jdbcTemplate.query 可以利用BeanPropertyRowMapper来映射
实验七
占位符参数:? #{} 顺序前往不能乱 ,传参的时候一定注意
具名参数:(剧名参数,参数不是占位符,而是一个变量名) 不用关心顺序
:empName 操作时将目标放到map作为key <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" > <constructor-arg name="dataSource" ref="comboPooledDataSource"></constructor-arg> </bean>