spring jdbc查询 依赖JdbcTemplate这个类模版封装JDBC的操作

 1 package cn.itcast.spring.jdbc;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.jdbc.core.support.JdbcDaoSupport;
 6 
 7 public class PersonDao extends JdbcDaoSupport{
 8     public void update(){
 9         this.getJdbcTemplate().execute("update person set pname='a' where pid=3");
10     }
11     
12     public void query(){
13         List<Person> persons = this.getJdbcTemplate().query("select * from person", new PersonRowMapper());
14         for(Person person:persons){
15             System.out.println(person.getPname());
16         }
17     }
18 }

 

 1 package cn.itcast.spring.jdbc;
 2 
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 
 6 import org.springframework.jdbc.core.RowMapper;
 7 
 8 public class PersonRowMapper implements RowMapper{
 9 
10     @Override
11     public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
12         // TODO Auto-generated method stub
13         Person person = new Person();
14         person.setPid(rs.getLong("pid"));
15         person.setPname(rs.getString("pname"));
16         person.setPsex(rs.getString("psex"));
17         return person;
18     }
19     /**
20      * crud做一下
21      */
22 
23 }

 

1 public class PersonTest {
2     @Test
3     public void test(){
4         ApplicationContext context = new ClassPathXmlApplicationContext("cn/itcast/spring/jdbc/applicationContext.xml");
5         PersonDao personDao = (PersonDao)context.getBean("personDao");
6         personDao.query();
7     }
8 }

 

 

你可能感兴趣的:(JdbcTemplate)