码迷,mamicode.com
首页 > 数据库 > 详细

spring jdbcTemplate

时间:2016-12-09 00:21:22      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:count   query   文件   imp   balance   blog   find   .net   object   

一、配置

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

标签:count   query   文件   imp   balance   blog   find   .net   object   

原文地址:http://www.cnblogs.com/hy87/p/6124108.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!