jdbcDaoSupport簡介
JdbcDaoSupport是JDBC數據訪問對象的超類。它與特定的數據源相關聯。spring Inversion of Control (IOC)容器或BeanFactory負責獲得相應數據源的配置詳細信息,並將其與JdbcDaoSupport相關聯。這個類最重要的功能就是使子類可以使用JdbcTemplate對象。
JdbcTemplate是Spring JDBC框架中最重要的類。引用文獻中的話:“它簡化了JDBC的使用,有助於避免常見的錯誤。它執行核心JDBC工作流,保留應用代碼以提供SQL和提取結果。”這個類通過執行下面的樣板任務來幫助分離JDBC DAO代碼的靜態部分:
◆從數據源檢索連接。
◆準備合適的聲明對象。
◆執行SQL CRUD操作。
◆遍歷結果集,然後將結果填入標準的collection對象。
◆處理SQLException異常並將其轉換成更加特定於錯誤的異常層次結構。
1、寫一個jdbc.properties數據連接池
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/test
jdbc.username=root
jdbc.password=123456
2、寫一個PersonDao類繼承JdbcDaoSupport
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class PersonDao extends JdbcDaoSupport {
public void savePerson(String sql)
{
this.getJdbcTemplate().execute(sql);
}
}
3、寫applicationContext.xml配置文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="datasource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="persondao1" class="com.zhiyou.dao.PersonDao">
<property name="dataSource">
<ref bean="datasource"/>
</property>
</bean>
4、寫一個PersonDaoTest的測試類
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PersonDaoTest {
@Test
public void test1()
{
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao personDao=(PersonDao)context.getBean("persondao1");
personDao.savePerson("insert into persons (pid,pname,pdesc) values ('007','wmy','123456') ");
//personDao.savePerson("insert into person(name,description) values('aa','aa')");
}
}
最後就可以插入數據了