首页 > 代码库 > spring jdbcTemplate
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); } }
spring jdbcTemplate
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。