步骤1.书写需要测试的各种类
①开启mysql数据库,并新建表,插入数据。一般表明对应着类名,字段对应着类的属性名。
//②设置类的属性名(为了测试,我们对应着数据库表的字段),并配置get、set方法
@Component
public class Employer {
private int id;
private String name;
private String email;
private int did;
//③新建对应employer的操作类
@Component
public class EmployerDao {
//使用jdbctemplate,自动装载
@Autowired
private JdbcTemplate jt;
public Employer get(int i){
String sql="select * from employee where id=?";
RowMapper<Employer> rm = new BeanPropertyRowMapper<>(Employer.class);
Employer e = jt.queryForObject(sql, rm,i);
return e;
}
④配置jdbc.properties,内容如下:
jdbc.user=root
jdbc.password=密码
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/数据库名
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
2.在spring配置xml里进行配置。其中包括bean的配置(对于bean我们使用注释装载的方式),数据源的配置,以及JdbcTemplate的配置
<!--扫描包,加载bean-->
<context:component-scan base-package="包名"></context:component-scan>
<!--加载jdbc文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="minPoolSize" value="${jdbc.maxPoolSize}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
</bean>
<!-- 配置spring的template -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
3.使用JUtil进行测试。
ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
@Test
public void test() {
EmployerDao ed = (EmployerDao) ac.getBean("employerDao");
Employer e = ed.get(2);
System.out.println(e);
}
小结:在实际配置中,总是报数据库连不上的错误,发现问题是没有配置c3p0的class类。