spring jdbcTemplate
一、配置
1、配置spring加入jar包和spring的配置文件
2、使用c3p0配置dataSource:
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean>
3、配置springTemplate:
<!-- 配置jdbcTemplate --> <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
二、使用示例:
package com.hy.dao; import java.net.SocketException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.hy.exception.AccountException; import com.hy.exception.StockException; @Repository("bookShopDao") public class BookShopDaoImpl implements BookShopDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public int findBookPriceByIsbn(String isbn) { String sql = "select price from book where isbn = ?"; return jdbcTemplate.queryForObject(sql, Integer.class, isbn); } @Override public void updateBookStock(String isbn) { String sql2 = "select stock from book_stock where isbn = ?"; int stock = jdbcTemplate.queryForObject(sql2, Integer.class, isbn); if (stock == 0) { throw new StockException("库存不足"); } String sql = "update book_stock set stock = stock - 1 where isbn = ?"; jdbcTemplate.update(sql, isbn); } @Override public void updateUserAccount(String username, int price) { String sql2 = "select balance from account where username = ?"; int balance = jdbcTemplate.queryForObject(sql2, Integer.class, username); if (balance < price) { throw new AccountException("余额不足"); } String sql = "update account set balance = balance - ? where username = ?"; jdbcTemplate.update(sql, price, username); } }
邮箱:wangh_2@sina.com