spring与jdbc 整合配置

来源:互联网 发布:node.js 后端开发 编辑:程序博客网 时间:2024/05/16 10:09

spring-jdbc.xml配置:

        <!-- 导入资源文件 --><context:property-placeholder location="jdbc.properties" /><!-- 配置 c3p0 数据库连接池 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driverClass}"></property><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property><property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property><property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property></bean><!-- 配置 spring 的JdbcTemplate --><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  <property name="dataSource" ref="dataSource"></property></bean>

测试:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:com/spring/Jdbc/spring-jdbc.xml")public class jdbcTest {@Autowiredprivate DataSource dataSource;@Autowiredprivate JdbcTemplate jdbcTemplate;/* * 测试数据库连接 */@Testpublic void TestdataSource() throws SQLException {System.out.println(dataSource.getConnection());}/* * 测试 insert update delete */@Testpublic void TestUpdate(){String sql="update account set name = ? where id = ? ";jdbcTemplate.update(sql, "dd",3);}/* * 执行批量更新:批量的 insert update delete * batchArgs 是 Object[] 数组的集合 */@Testpublic void TestBatchUpdate(){String sql="insert into account (name,money) values ( ? , ? )";List<Object[]> batchArgs=new ArrayList<>();batchArgs.add(new Object[]{"cc",1200});batchArgs.add(new Object[]{"ee",2000});batchArgs.add(new Object[]{"ff",3000});batchArgs.add(new Object[]{"mm",4000});jdbcTemplate.batchUpdate(sql, batchArgs);}}


0 0
原创粉丝点击