Spring 的数据库开发
#Spring 中 JDBC 模板的作用
JDBC 模板负责数据库资源管理和错误处理;
# 熟悉 SpringJDBC 的配置
配置数据源和 jdbc 模板
- <?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-4.3.xsd">
- <!-- 1 配置数据源 -->
- <bean id="dataSource" class=
- "org.springframework.jdbc.datasource.DriverManagerDataSource">
- <!-- 数据库驱动 -->
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <!-- 连接数据库的 url -->
- <property name="url" value="jdbc:mysql://localhost:3306/spring" />
- <!-- 连接数据库的用户名 -->
- <property name="username" value="root" />
- <!-- 连接数据库的密码 -->
- <property name="password" value="root" />
- </bean>
- <!-- 2 配置 JDBC 模板 -->
- <bean id="jdbcTemplate"
- class="org.springframework.jdbc.core.JdbcTemplate">
- <!-- 默认必须使用数据源 -->
- <property name="dataSource" ref="dataSource" />
- </bean>
- <!-- 定义 id 为 accountDao 的 Bean-->
- <bean id="accountDao" class="com.sjl.jdbc.AccountDaoImpl">
- <!-- 将 jdbcTemplate 注入到 accountDao 实例中 -->
- <property name="jdbcTemplate" ref="jdbcTemplate" />
- </bean>
- </beans>
- #jdbcTemplate 类中几个常用方法
update() 方法可以完成插入, 更新, 删除, 并返回受影响的行数;
int update(String sql) sql 语句
int update(String sql,PreparedStatementSetter pss) sql 语句, 预编译参数
int update(String sql,Object...args) sql 语句, 可变长参数
query() 方法
List query(String sql,RowMapper rowMapper) sql 语句, 数据库中的记录, java 实体的映射的对象
queryForObject(String sql,RowMapper rowMapper,Object...args) sql 语句, 数据库中的记录, java 实体的映射的对象, 变长参数
说明: 除了导入 Spring 的基本包, 还要导入 connector(驱动连接包),jdbc(连接) 和 ex(事务) 包;
- #Account.java(实体类)
- package com.sjl.jdbc;
- public class Account {
- private Integer id; // 账户 id
- private String username; // 用户名
- private Double balance; // 账户余额
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public Double getBalance() {
- return balance;
- }
- public void setBalance(Double balance) {
- this.balance = balance;
- }
- public String toString() {
- return "Account [id=" + id + ","
- + "username=" + username +
- ", balance=" + balance + "]";
- }
- }
- # 接口的方法的实现
- package com.sjl.jdbc;
- import java.util.List;
- public interface AccountDao {
- // 添加
- public int addAccount(Account account);
- // 更新
- public int updateAccount(Account account);
- // 删除
- public int deleteAccount(int id);
- // 通过 id 查询
- public Account findAccountById(int id);
- // 查询所有账户
- public List<Account> findAllAccount();
- }
- # 接口的实现类
- package com.sjl.jdbc;
- import java.util.List;
- import org.springframework.jdbc.core.BeanPropertyRowMapper;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.core.RowMapper;
- public class AccountDaoImpl implements AccountDao {
- // 声明 JdbcTemplate 属性及其 setter 方法
- private JdbcTemplate jdbcTemplate;
- public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
- this.jdbcTemplate = jdbcTemplate;
- }
- // 添加账户
- public int addAccount(Account account) {
- // 定义 SQL
- String sql = "insert into account(username,balance) value(?,?)";
- // 定义数组来存放 SQL 语句中的参数
- Object[] obj = new Object[] {
- account.getUsername(),
- account.getBalance()
- };
- // 执行添加操作, 返回的是受 SQL 语句影响的记录条数
- int num = this.jdbcTemplate.update(sql, obj);
- return num;
- }
- // 更新账户
- public int updateAccount(Account account) {
- // 定义 SQL
- String sql = "update account set username=?,balance=? where id = ?";
- // 定义数组来存放 SQL 语句中的参数
- Object[] params = new Object[] {
- account.getUsername(),
- account.getBalance(),
- account.getId()
- };
- // 执行添加操作, 返回的是受 SQL 语句影响的记录条数
- int num = this.jdbcTemplate.update(sql, params);
- return num;
- }
- // 删除账户
- public int deleteAccount(int id) {
- // 定义 SQL
- String sql = "delete from account where id = ?";
- // 执行添加操作, 返回的是受 SQL 语句影响的记录条数
- int num = this.jdbcTemplate.update(sql, id);
- return num;
- }
- // 通过 id 查询账户数据信息
- public Account findAccountById(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);
- }
- // 查询所有账户信息
- public List<Account> findAllAccount() {
- // 定义 SQL 语句
- String sql = "select * from account";
- // 创建一个新的 BeanPropertyRowMapper 对象
- RowMapper<Account> rowMapper =
- new BeanPropertyRowMapper<Account>(Account.class);
- // 执行静态的 SQL 查询, 并通过 RowMapper 返回结果
- return this.jdbcTemplate.query(sql, rowMapper);
- }
- }
- # 测试类
- package com.sjl.jdbc;
- import java.util.List;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import
- org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.jdbc.core.JdbcTemplate;
- public class JdbcTemplateTest {
- /**
- * 使用 execute() 方法建表
- */
- // public static void main(String[] args) {
- // // 加载配置文件
- // ApplicationContext applicationContext =
- // new ClassPathXmlApplicationContext("applicationContext.xml");
- // // 获取 JdbcTemplate 实例
- // JdbcTemplate jdTemplate =
- // (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
- // // 使用 execute() 方法执行 SQL 语句, 创建用户账户管理表 account
- // jdTemplate.execute("create table account(" +
- // "id int primary key auto_increment," +
- // "username varchar(50)," +
- // "balance double)");
- // System.out.println("账户表 account 创建成功!");
- // }
- @Test
- public void mainTest() {
- // 加载配置文件
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- // 获取 JdbcTemplate 实例
- JdbcTemplate jdTemplate =
- (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
- // 使用 execute() 方法执行 SQL 语句, 创建用户账户管理表 account
- jdTemplate.execute("create table account(" +
- "id int primary key auto_increment," +
- "username varchar(50)," +
- "balance double)");
- System.out.println("账户表 account 创建成功!");
- }
- @Test
- public void addAccountTest() {
- // 加载配置文件
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- // 获取 AccountDao 实例
- AccountDao accountDao =
- (AccountDao) applicationContext.getBean("accountDao");
- // 创建 Account 对象, 并向 Account 对象中添加数据
- Account account = new Account();
- account.setUsername("tom");
- account.setBalance(1000.00);
- // 执行 addAccount() 方法, 并获取返回结果
- int num = accountDao.addAccount(account);
- if (num> 0) {
- System.out.println("成功插入了" + num + "条数据!");
- } else {
- System.out.println("插入操作执行失败!");
- }
- }
- @Test
- public void updateAccountTest() {
- // 加载配置文件
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- // 获取 AccountDao 实例
- AccountDao accountDao =
- (AccountDao) applicationContext.getBean("accountDao");
- // 创建 Account 对象, 并向 Account 对象中添加数据
- Account account = new Account();
- account.setId(1);
- account.setUsername("tom");
- account.setBalance(2000.00);
- // 执行 updateAccount() 方法, 并获取返回结果
- int num = accountDao.updateAccount(account);
- if (num> 0) {
- System.out.println("成功修改了" + num + "条数据!");
- } else {
- System.out.println("修改操作执行失败!");
- }
- }
- @Test
- public void deleteAccountTest() {
- // 加载配置文件
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- // 获取 AccountDao 实例
- AccountDao accountDao =
- (AccountDao) applicationContext.getBean("accountDao");
- // 执行 deleteAccount() 方法, 并获取返回结果
- int num = accountDao.deleteAccount(1);
- if (num> 0) {
- System.out.println("成功删除了" + num + "条数据!");
- } else {
- System.out.println("删除操作执行失败!");
- }
- }
- @Test
- public void findAccountByIdTest() {
- // 加载配置文件
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- // 获取 AccountDao 实例
- AccountDao accountDao =
- (AccountDao) applicationContext.getBean("accountDao");
- // 执行 findAccountById() 方法
- Account account = accountDao.findAccountById(1);
- System.out.println(account);
- }
- @Test
- public void findAllAccountTest() {
- // 加载配置文件
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- // 获取 AccountDao 实例
- AccountDao accountDao =
- (AccountDao) applicationContext.getBean("accountDao");
- // 执行 findAllAccount() 方法, 获取 Account 对象的集合
- List<Account> account = accountDao.findAllAccount();
- // 循环输出集合中的对象
- for (Account act : account) {
- System.out.println(act);
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2948250.html