Spring之jdbc 数据库操作
核心:JdbcTemplate对象包装了所有增删改查的操作
xml:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"></property>
</bean>
<bean id="customerDao" class="jdbc.CustomerDaoBean">
<property name="jdbcTemplate" ref="jdbcTemplate"></property> //在CustomerDaoBean类有变量private JdbcTemplate jdbcTemplate; set方法
</bean>
接口类: 省略...
CustomerDaoBean类:
public class CustomerDaoBean implements CustomerDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void insert(Customer customer) {
jdbcTemplate.update("insert into customer(name,age)values(?,?)", customer.getName(), customer.getAge());
}
@Override
public Customer findById(int id) {
String sql = "select * from customer where id=?";
return jdbcTemplate.queryForObject(sql,new Object[]{id},new CustomerRowMapper());
}
@Override
public List<Customer> findAll() {
return jdbcTemplate.query("select * from customer", new CustomerRowMapper());
}
class CustomerRowMapper implements RowMapper<Customer>{ //RowMapper单独包装成内部类,此段代码不用重复写,简化--->包装Customer对象
@Override
public Customer mapRow(ResultSet arg0, int arg1) throws SQLException {
Customer customer = new Customer();
customer.setId(arg0.getInt("id"));
customer.setName(arg0.getString("name"));
customer.setAge(arg0.getInt("age"));
return customer;
}
}
}
测试类:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("jdbc/bean2.xml");
CustomerDaoBean customerDaoBean = applicationContext.getBean("customerDaoBean", CustomerDaoBean.class);
/*
customer.setName("lisi");
customer.setAge(23);
customerDaoBean.insert(customer);
*/
Customer customer = customerDaoBean.findById(2);
System.out.println(customer.getId()+":"+customer.getName());
/*
List<Customer> customers = customerDaoBean.findAll();
for (Customer customer : customers) {
System.out.println(customer.getId()+":"+customer.getName());
}*/

浙公网安备 33010602011771号