三、spring入门之整合jdbc
通过继承org.springframework.jdbc.core.support.JdbcDaoSupport类,通过Spring的xml向该类中注入连接池
在子类中使用org.springframework.jdbc.core.support.JdbcDaoSupport.getJdbcTemplate()方法获取JdbcTemplate对象
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<context:property-placeholder location="classpath:c3p0.properties" />
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean name="UserDaoImpl" class="cn.zw.jdbc.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
package cn.zw.jdbc;
/**
*
* @ClassName: UserDao
* @Description:TODO(Dao的接口)
* @date: 2018年12月3日 下午3:25:57
*/
public interface UserDao {
void save();
void delete();
void update();
void select();
}
package cn.zw.jdbc;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
/**
*
* @ClassName: UserDaoImpl
* @Description:TODO(模拟数据层dao的操作)
* @date: 2018年12月3日 下午3:28:28
*/
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
@Override
public void save() {
System.out.println("增加");
}
@Override
public void delete() {
System.out.println("删除");
}
@Override
public void update() {
getJdbcTemplate().update("update Sutdent s set s.name = 'xiaoming' where code = '97001'");
}
@Override
public void select() {
System.out.println("查询");
}
}
package cn.zw.jdbc;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context7.xml")
public class DemoTest {
@Autowired
private UserDaoImpl userDaoImpl;
@Test
public void fun() throws Exception {
userDaoImpl.update();
}
}