1. 程式人生 > >JavaEE Spring JDBC——query()資料庫查詢

JavaEE Spring JDBC——query()資料庫查詢

在JdbcTemplate類中還提供了大量的query()方法來處理各種對資料庫的查詢操作

下面通過一個案例來演示query方法的使用

1、向資料表account中插入幾條資料,插入後的資料如下所示:

2、在AccountDao中建立一個通過id查詢單個賬戶,和查詢所有賬戶的方法,程式碼如下所示:

package com.itheima.jdbc;

import java.util.List;

public interface AccountDao {

	//新增
	public int addAccount(Account account) ;
	//更新
	public int upAccount(Account account) ;
	//刪除
	public int deleteAccount(int id) ;
	//通過id查詢單個賬號
	public Account findAccount(int id);
	//查詢所有賬號
	public List<Account> findAccount();

}

3、在AccountDao的實現類AccountDaoImpl中,實現介面中的方法,並使用query()方法分別進行查詢,其程式碼如下所示:

//通過id查詢賬戶資料資訊
	public Account findAccountById(int id) {
		String sql= "select * from account where id = ?";
		//建立一個新的BeanPropertyRowMapper物件
		BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
		return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
	}

	@Override
	public List<Account> findAllAccount() {
		String sql= "select * form account ";
		//建立一個新的BeanPropertyRowMapper物件
		BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
		return this.jdbcTemplate.query(sql, rowMapper);
	}

4、在測試類JdbcTemplateTest中新增一個測試方法findAccountByIdTest()來測試條件查詢

其程式碼如下:

@Test
	public  void findAccountTestByIdTest() {
		ApplicationContext lizi = new ClassPathXmlApplicationContext("applicationContext.xml");
		AccountDao accountDao = (AccountDao)lizi.getBean("accountDao");
		
		//執行findAccountByIdTest方法,查詢id為1的賬號,並獲取返回結果
		Account account=accountDao.findAccountById(1);
		System.out.println(account);
	}

執行結果如下所示:

5、測試完條件查詢之後,接下來測試查詢所有使用者賬戶資訊的方法。在測試類JdbcTemplateTest中新增一個測試方法findAllAccountTest()來測試查詢所有使用者賬戶資訊的方法是否正確

@Test
	public  void findAllAccountTestTest() {
		ApplicationContext lizi = new ClassPathXmlApplicationContext("applicationContext.xml");
		AccountDao accountDao = (AccountDao)lizi.getBean("accountDao");
		
		//執行findAllAccountTest方法,查詢所有的賬號,並獲取返回結果
		List<Account> account=accountDao.findAllAccount();
		for(Account account2 : account)
			System.out.println(account2);
	}

執行結果如下:

可能有兄弟要問,好像多了一個,這是我在寫完程式碼執行的時候,不小心點到了插入測試單元,所以又插入了一個