1. 程式人生 > >spring-c3p0-01

spring-c3p0-01

配置

    <context:annotation-config />
    <context:component-scan base-package="cn.mldn" />
    <context:property-placeholder location="classpath:database.properties"/>
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass"
value="${db.driver}" /> <property name="jdbcUrl" value="${db.url}" /> <property name="user" value="${db.user}" /> <property name="password" value="${db.password}" /> <property name="maxPoolSize" value="${pool.max}" /> <property name="minPoolSize"
value="${pool.min}" /> <property name="initialPoolSize" value="${pool.init}" /> <property name="maxIdleTime" value="${pool.idle}" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"
ref="dataSource"/> </bean>

database.properties

db.driver=org.gjt.mm.mysql.Driver
db.url=jdbc:mysql://localhost:3306/mldn
db.user=root
db.password=mysqladmin
pool.max=100
pool.min=20
pool.init=10
pool.idle=100

 

測試:

    public static void main(String[] args) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        JdbcTemplate jt = ctx.getBean("jdbcTemplate",JdbcTemplate.class);
        String sql = "SELECT mid FROM member ";
        List<String> all = jt.queryForList(sql, String.class);
        System.out.println(all);

    }

 JdbcDAOsupport

import cn.mldn.dao.IMemberDAO;
import cn.mldn.vo.Member;

public class MemberDAOImpl extends JdbcDaoSupport implements IMemberDAO {

    @Autowired
    public MemberDAOImpl(JdbcTemplate jdbcTemplate) {    //注入  jdbcTemplate 
        super.setJdbcTemplate(jdbcTemplate);        // 由JdbcDaoSupport管理 jdbcTemplate 
    }
    
    @Override
    public boolean doCreate(Member vo) throws Exception {
        this.getJdbcTemplate().update("");    //執行完畢後由JdbcDaoSupport負責資料庫關閉
        return false;
    }
}