JdbcTemplate類中常用的查詢方法?
方法 | 說明 |
List query(String sql, RowMapper rowMapper) | 執行String類型參數提供的SQL語句,并通過參數rowMapper返回一個List類型的結果。 |
List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper) | 根據String類型參數提供的SQL語句創建PreparedStatement對象,通過參數rowMapper將結果返回到List中。 |
List query(String sql,Object[] args, RowMapper rowMapper) | 使用Object[]的值來設置SQL語句中的參數值,rowMapper是個回調方法,直接返回List類型的數據。 |
queryForObject(String sql,RowMapper rowMapper,Object… args) | 將args參數綁定到SQL語句中,并通過參數rowMapper返回一個Object類型的單行記錄。 |
queryForList(String sql,Object[] args, class<T> elementType) | 該方法可以返回多行數據的結果,但必須返回列表,args參數是sql語句中的參數,elementType參數返回的是List數據類型。 |
????????了解了JdbcTemplate類中幾個常用的query()方法后,接下來通過一個具體的案例演示query()方法的使用,案例實現步驟如下。
1、插入數據
????????向數據表account中插入幾條數據。
insert into 'account'('id','username','balance')
values (1,'zhangsan',100),(3,'lisi',500),(4,'wangwu',300);
2、編寫查詢方法
????????在前面的AccountDao接口中,聲明findAccountById()方法,通過id查詢單個賬戶信息;聲明findAllAccount()方法,用于查詢所有賬戶信息。
// 通過id查詢
public Account findAccountById(int id);
// 查詢所有賬戶
public List<Account> findAllAccount();
3、實現查詢方法
????????在前面的的AccountDaoImpl類中,實現AccountDao接口中的findAccountById()方法和findAllAccount()方法,并調用query()方法分別進行查詢。
// 通過id查詢單個賬戶信息public Account findAccountById(int id) {//定義SQL語句String sql = "select * from account where id = ?";// 創建一個新的BeanPropertyRowMapper對象RowMapper<Account> rowMapper =new BeanPropertyRowMapper<Account>(Account.class);// 將id綁定到SQL語句中,并通過RowMapper返回一個Object類型的單行記錄return this.jdbcTemplate.queryForObject(sql, rowMapper, id);}//查詢所有賬戶信息public List<Account> findAllAccount() {// 定義SQL語句String sql = "select * from account";// 創建一個新的BeanPropertyRowMapper對象RowMapper<Account> rowMapper =new BeanPropertyRowMapper<Account>(Account.class);// 執行靜態的SQL查詢,并通過RowMapper返回結果return this.jdbcTemplate.query(sql, rowMapper);}
4、測試條件查詢
????????創建測試類FindAccountByIdTest,用于測試條件查詢。
public class FindAccountByIdTest {public static void main(String[] args) {// 加載配置文件ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");// 獲取AccountDao實例AccountDao accountDao =(AccountDao) applicationContext.getBean("accountDao");Account account = accountDao.findAccountById(1);System.out.println(account); }
}
5、測試查詢所有用戶信息
????????創建測試類FindAllAccountTest,用于查詢所有用戶賬戶信息。
public class FindAllAccountTest {public static void main(String[] args) {// 加載配置文件ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");// 獲取AccountDao實例AccountDao accountDao =(AccountDao) applicationContext.getBean("accountDao");List<Account> account = accountDao.findAllAccount(); // 執行方法for (Account act : account) {// 循環輸出集合中的對象System.out.println(act); } }
}
6、查看運行結果
????????在IDEA中啟動FindAllAccountTest類,控制臺會輸出結果。
Account [id=1,username=zhangsan,balance=100.0]
Account [id=3,username=lisi,balance=500.0]
Account [id=4,username=wangwu,balance=300.0]