JavaEE Spring JDBC——query()数据库查询

本文介绍了在JavaEE Spring项目中使用JdbcTemplate的query方法进行数据库查询的操作。首先展示了向account表中插入数据,然后在AccountDao接口及实现类中定义并实现了通过id查找单个账户和查询所有账户的方法。接着在测试类JdbcTemplateTest中,对这两个查询方法进行了单元测试,验证了query方法的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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);
	}

运行结果如下:

可能有兄弟要问,好像多了一个,这是我在写完代码运行的时候,不小心点到了插入测试单元,所以又插入了一个

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值