1.创建项目,添加依赖的jar
1.1 spring-bean.jar
1.2 spring-context.jar
1.3 spring-core.jar
1.4 spring-expression.jar
1.5 mysql-connector-java.jar √
1.6 spring-jdbc.jar √
1.7 commons-dbcp.jar √
1.8 commons-pool.jar √
1.9 spring-tx.jar √
2.创建Spring的配置文件
3.配置数据库连接池(数据源)
3.1 Apache commons DBCP √
3.2 C3P0
3.3 Alibaba Dridu
<!-- 配置数据库连接池(数据源) -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<!-- 连接数据库的四个参数 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mydb"/>
<proprety name="username" value="root"/>
<proprety name="password" value="rootroot"/>
</bean>
4.配置Spring的JdbcTemplate,并将数据库连接池注入
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource" />
</bean>
5.写自己的Dao,并将JdbcTemplate注入
<bean id="studentDao" class="com.kaishengit.dao.StudentDao">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
6.在Dao中写保存的方法
public class StudentDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void save(Student student) {
String sql = "insert into t_student(stuName,stuAddress,stuScore) values(?,?,?)";
jdbcTemplate.update(sql,student.getStuName(),student.getStuAddress(),student.getStuScore());
}
}
7. 测试保存方法
@Test
public void save() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
StudentDao studentDao = (StudentDao) ctx.getBean("studentDao");
Student student = new Student();
student.setStuName("Spring");
student.setStuAddress("美国");
student.setStuScore(88);
studentDao.save(student);
}
8. 查询方法
8.1 查询单个对象使用的是JdbcTemplate中的queryForObject()方法
8.2 查询对象集合使用的是JdbcTemplate中的query方法
8.3 需要在上面的两个方法中传入RowMapper集合的实现类对象。实现类一般为内部类
//内部类
private class StudentRowMapper implements RowMapper<Student> {
@Override
public Student mapRow(ResultSet rs, int arg1) throws SQLException {
//将结果集(resultSet)转换为Student类对象
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setStuName(rs.getString("stuName"));
stu.setStuAddress(rs.getString("stuAddress"));
stu.setStuScore(rs.getInt("stuScore"));
return stu;
}
}
8.4 查询单个对象
String sql = "select * from t_student where id = ?";
return jdbcTemplate.queryForObject(sql, new StudentRowMapper(),id);
8.5 查询所有对象
public List<Student> findAll() {
String sql = "select * from t_student";
return jdbcTemplate.query(sql, new StudentRowMapper());
}
8.6 聚合函数查询
public int count() {
String sql = "select count(*) from t_student";
return jdbcTemplate.queryForObject(sql, Integer.class);
}
|
|