美文网首页
Spring学习 一 JDBC配置文件

Spring学习 一 JDBC配置文件

作者: Mon7ey | 来源:发表于2018-05-04 09:31 被阅读6次
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">
    
    <!-- 读取数据库配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 1. 将连接池放入spring容器 -->
    <bean name="dataSource"
        class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <bean name="accountDao" class="com.mon7ey.spring.dao.AccoutnDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <bean name="accountService" class="com.mon7ey.spring.service.AccountServiceImpl">
        <property name="ad" ref="accountDao"></property>
    </bean>

</beans>
dp.properties
jdbc.jdbcUrl=jdbc:mysql:///hib_demo
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
AccoutnDaoImpl
public class AccoutnDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Override
    public void increaseMoney(Integer id, Double money) {
        super.getJdbcTemplate().
            update("update t_account set money = money + ? where id = ?",money,id);
    }

    @Override
    public void decreaseMoney(Integer id, Double money) {
        super.getJdbcTemplate().
        update("update t_account set money = money - ? where id = ?",money,id);

    }

}
AccountServiceImpl
public class AccountServiceImpl implements AccountService {

    private AccountDao ad;
    
    public void setAd(AccountDao ad) {
        this.ad = ad;
    }
    
    @Override
    public void transfer(Integer from, Integer to, Double money) {
        // 减钱
        ad.decreaseMoney(from, money);
        // 加钱
        ad.increaseMoney(to, money);
        
    }
}
image.png

相关文章

网友评论

      本文标题:Spring学习 一 JDBC配置文件

      本文链接:https://www.haomeiwen.com/subject/izqilftx.html