Spring的数据库开发
Spring的JDBC模块负责数据库资源管理和错误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从烦琐的数据库操作中解脱出来,从而将更多的精力投入到编写业务逻辑中
1. Spring JDBC
1.1 Spring JdbcTemplate的解析
针对数据库的操作,Spring框架提供了JdbcTemplate类,该类是Spring框架数据抽象层的基础,其他更高层次的抽象类却是构建于JdbcTemplate类之上。可以说,JdbcTemplate类是Spring JDBC的核心类。
JdbcTemplate类的继承关系十分简单。它继承自抽象类JdbcAccessor,同时实现了JdbcOperations接口
JdbcTemplate类的直接父类是JdbcAccessor,该类为子类提供了一些访问数据库时使用的公共属性
属性 | 作用 |
---|---|
DataSource | 其主要功能是获取数据库连接,具体实现时还可以引入对数据库连接的缓冲池和分布式事务的支持,它可以作为访问数据库资源的标准接口 |
SQLExceptionTranslator | org.springframework.jdbc.support.SQLExceptionTranslator接口负责对SQLException进行转译工作。通过必要的设置或者获取SQLExceptionTranslator中的方法,可以使JdbcTemplate在需要处理SQLException时,委托SQLExceptionTranslator的实现类来完成相关的转译工作 |
JdbcOperations接口定义了在JdbcTemplate类中可以使用的操作集合,包括添加、修改、查询和删除等操作
1.2 Spring JDBC的配置
Spring JDBC模块主要由4个包组成,分别是core(核心包)、dataSource(数据源包)、object(对象包)和support(支持包)
在Spring中,JDBC的配置是在配置文件applicationContext.xml中完成的,其配置模板下所示
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置JDBC模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" value="dataSource"></property>
</bean>
<!-- 配置注入类 -->
<bean id="xxx" class="Xxx">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
定义了3个Bean,分别是dataSource、jdbcTemplate和需要注入类的Bean。其中dataSource对应org.springframework.jdbc.datasource.DriverManagerDataSource类用于对数据源进行配置,jdbcTemplate对应的org.springframework.jdbc.core.JdbcTemplate类中定义了JdbcTemplate的相关配置
定义jdbcTemplate时,需要将dataSource注入到jdbcTemplate中,而其他需要使用jdbcTemplate的Bean,也需要将jdbcTemplate注入到该Bean中(通常注入到Dao类中,在Dao类中进行与数据库的相关操作)
2. Spring JdbcTemplate的常用方法
在JdbcTemplate类中,提供了大量的更新和查询数据库的方法,我们就是使用这些方法来操作数据库的
2.1 execute()
execute(String sql)方法能够完成执行SQL语句的功能
除基础包外引入三个包
1.xml文件配置
...省略,如模板
2.测试类
@Test
public void executeTest() {
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()
update()方法可以完成插入、更新和删除数据的操作
- 新添账户
1.account实现类
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public int addAccount(Account account) {
String sql ="insert into account (username,balance) value (?,?)";
Object[] objects = new Object[] {
account.getUsername(),
account.getBalance()
};
int num = this.jdbcTemplate.update(sql,objects);
return num;
}
@Override
public int updateAccount(Account account) {
String sql = "update account set username =?,balance=? where id=?";
Object[] objects = new Object[] {
account.getUsername(),
account.getBalance(),
account.getId()
};
int num = this.jdbcTemplate.update(sql,objects);
return num;
}
@Override
public int deleteAccount(int id) {
String sql = "delete from account where id=?";
int num = this.jdbcTemplate.update(sql,id);
return num;
}
2.xml文件配置
<!-- 配置注入类 -->
<bean id="accountDao" class="com.clarence.jdbc.AccountDaoImpl">
<!-- 将jdbcTemplate注入到accountDao实例中 -->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
3.测试类新添账户
@Test
public void addAcountTest() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AccountDao accountDao = (AccountDao)applicationContext.getBean("accountDao");
Account account = new Account();
account.setUsername("tom");
account.setBalance(1000.00);
int num = accountDao.addAccount(account);
System.out.println(num>0?"成功插入了"+num+"条数据":"插入失败");
}
运行结果
- 更新账户
1.测试类更新账户
@Test
public void updateAcountTest() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AccountDao accountDao = (AccountDao)applicationContext.getBean("accountDao");
Account account = new Account();
account.setId(1);
account.setUsername("tom");
account.setBalance(3000.00);
int num = accountDao.updateAccount(account);
System.out.println(num>0?"成功更新了"+num+"条数据":"更新失败");
}
运行结果
- 删除账户
@Test
public void DeleteAcountTest() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AccountDao accountDao = (AccountDao)applicationContext.getBean("accountDao");
int num = accountDao.deleteAccount(1);
System.out.println(num>0?"成功删除了"+num+"条数据":"删除失败");
}
运行结果
2.3 query()
JdbcTemplate类中还提供了大量的query()方法来处理各种对数据库表的查询操作
1.接口定义方法
Account findAccountById(int id);
List<Account> findAllAccount();
2.实现类
@Override
public Account findAccountById(int id) {
String sql = "select * from account where id=?";
RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(
Account.class);
//将id绑定到sql语句中,通过RowMapper返回一个Object类型的单行记录
return this.jdbcTemplate.queryForObject(sql, rowMapper,id);
}
@Override
public List<Account> findAllAccount() {
String sql = "select * from account";
RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
//this.jdbcTemplate.queryForList(sql);返回的是一个List<Map<String,Object>>
return this.jdbcTemplate.query(sql,rowMapper);
}
3.测试类
@Test
public void findAccountByIdTest() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AccountDao accountDao = (AccountDao)applicationContext.getBean("accountDao");
Account account = accountDao.findAccountById(4);
System.out.println(account);
}
@Test
public void findAllAccountTest() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AccountDao accountDao = (AccountDao)applicationContext.getBean("accountDao");
List<Account> account = accountDao.findAllAccount();
for (Account account2 : account) {
System.out.println(account2);
}
}
运行结果:
findAccountByIdTest()运行结果
findAllAccountTest()运行结果
3. 总结
在整合框架的运用下,数据库操作过程交给了MyBatis。