版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/82871783
在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);
}
运行结果如下:
可能有兄弟要问,好像多了一个,这是我在写完代码运行的时候,不小心点到了插入测试单元,所以又插入了一个