继续从上一个进行了insert update delete的地方开始用query进行find和list操作
在Dao接口中再写两个方法:
1 package com.zyk.database; 2 3 import java.util.List; 4 5 public interface AccountDao { 6 public int add(Account account); 7 public int update(Account account); 8 public int delete(int id); 9 public Account find(int id); 10 public List<Account> listAll(); 11 }
在DaoImpl中实现这两个方法:
1 @Override 2 public Account find(int id) { 3 String sql="select * from account where id=?"; 4 RowMapper<Account> rowMapper=new BeanPropertyRowMapper<Account>(Account.class); 5 return this.jdbcTemplate.queryForObject(sql, rowMapper,id); 6 } 7 8 @Override 9 public List<Account> listAll() { 10 // TODO Auto-generated method stub 11 String sql="select * from account"; 12 RowMapper<Account> rowMapper=new BeanPropertyRowMapper<Account>(Account.class); 13 return this.jdbcTemplate.query(sql, rowMapper); 14 }
FindTest进行测试查找数据库:
1 package com.zyk.database; 2 3 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7 public class FindTest { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); 12 AccountDao accountDao= (AccountDao)applicationContext.getBean("accountDao"); 13 Account account=accountDao.find(2); 14 System.out.println(account); 15 16 } 17 18 }
截图:
ListAll进行显示:
1 package com.zyk.database; 2 3 import java.util.List; 4 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.support.ClassPathXmlApplicationContext; 7 8 public class ListAllTest { 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); 13 AccountDao accountDao=(AccountDao)applicationContext.getBean("accountDao"); 14 List<Account> accounts=accountDao.listAll(); 15 for(Account act: accounts) { 16 System.out.println(act); 17 } 18 } 19 20 }
截图:
总结:
RowMapper<Account> rowMapper=new BeanPropertyRowMapper<Account>(Account.class)
是创建一个新的BeanPropertyRowMapper对象。
return this.jdbcTemplate.queryForObject(sql, rowMapper,id);
将id绑定到sql语句中,并通过rowMapper返回一个object类型的单行记录。