文章目录
源码:https://gitee.com/fenglifengli/springjdbctemplate.git
一、spring jdbc
1.1 JdbcTemplate解析
针对数据库的操作, Spring 框架提供了 ==JdbcTemplate ==类。他的继承关系如下:
JdbcAccessor:该类为子类提供了一些访问数据库时使用的
公共属性。
JdbcOperations:该接口接口定义了在 JdbcTemplate 类中可以使用的操作集合,包括添加、修改、
查询和删除等操作。
1.2 Spring Jdbc配置
在idea中创建一个maven项目,自行设置好依赖。在/src/main/
下面场景一个resources
文件夹,然后记得在Modules中将该目录设为资源文件。
主要配置驱动,数据源所在地址,访问数据库的用户名,访问数据库的密码。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--数据库驱动-->
<property name="driverClassName" value="com.mysql.jdbc.Driver "/>
<property name="url" value="jdbc:mysql://localhost:3306/spring"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--配置JDBC模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate ">
<!--必须使用数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置注入类-->
</beans>
二、spring template的常用方法
2.1 excute方法
该方法是用来执行sql代码的。例子
public static void main( String[] args )
{
System.out.println();
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate= (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
jdbcTemplate.execute("create table account("+
"id int primary key auto_increment,"+
"username varchar(50),"+
"balance double)");
System.out.println("账号表account创建成功");
}
该方法用于在数据库创建一张表。
2.2 update()方法
public int addAccount(Account account) {
Object objects[] = {
account.getAccount(), account.getBalance()
};
int num = jdbcTemplate.update("insert into account(username,balance) values(?,?)", objects);
return num;
}
测试
@Test
public void addAccount() {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/applicationContext.xml");
AccountDao accountDao= (AccountDao) applicationContext.getBean("accountDaoImpl");
Account account=new Account();
account.setAccount("fengli");
account.setBalance(100000000);
long result=accountDao.addAccount(account);
assertEquals(1l, 1l);
}
运行结果:
2.3 query()方法
有些方法,提供了对象映射关系功能。
@Override
public Account findAccountByld(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);
}
测试
@Test
public void findAccountByld(){
AccountDao accountDao = getAccountDao();
Account account=accountDao.findAccountByld(1);
System.out.println(account.toString());
}
运行结果: