Spring JDBC模块负责数据库资源管理,针对数据库操作,Spring框架提供了JdbcTemplate类,该类是Spring JDBC的核心类。
Spring JDBC主要由4个包组成:
Spring对数据库的操作都封装在了这几个包中,想要使用JDBC就需要对其进行配置,在Spring容器中,对JDBC的配置是在applicationContext.xml文件中进行的。
对于pom.xml里面配置导入相关依赖
关于DataSource
DataSource 通常被称为数据源,它包含连接池和连接池管理两个部分,习惯上也经常把 DataSource称为连接池 数据源和数据库连接不同,数据源无需创建多个,它是产生数据库连接的工厂,因此整个应用只需要一个数据源即可。
连接池的作用:
先创建一个连接对象,将该连接对象及其内容都放到连接池里面,用的时候去拿,用完了放回到连接池,从而避免了经常打开和关闭连接对象。
二、Spring JDBC Template 的常用方法
1.execute(String sql): 用于执行sql语句。
用一个创建数据库表的方法来演示该方法:
首先在数据库中创建一个名为spring的数据库。
然后创建一个web项目,并导入相应jar包。
第三步,创建applicationContext.xml配置文件,并进行数据源的配置。
(配置代码和上面的配置模板一样)
package chapter04;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDaoimplTest {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("ApplicationContext1.xml");
// UserDaoimpl userDaoimpl=(UserDaoimpl)ac.getBean("userDao");
// System.out.println(userDaoimpl.getJdbcTemplate());
JdbcTemplate jdbcTemplate=(JdbcTemplate)ac.getBean("jdbcTemplate");
//执行sql
jdbcTemplate.execute("CREATE TABLE account(" +
"id INT PRIMARY KEY ," +
"username VARCHAR(50)," +
"balance DOUBLE" +
")");
System.out.println("account表创建成功");
}
}
之后数据表被增加成功
jdbc实现增删改查的方法
update():用于执行插入,更新和删除操作。常用的方法如下图所示:
下面通过一个账户管理的案例来演示update()方法的使用。
首先创建一个Account实体类 。
package chapter04;
public class Account {
private Integer id;
private String username;
private Double balance;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", username='" + username + '\'' +
", balance=" + 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;
}
}
写出一个AccountDao接口
package chapter04;
import java.security.AccessControlContext;
import java.util.List;
public interface AccountDao {
public Integer addaccount(Account account);
public Integer deleteAccount(Integer id);
public Integer updateAccount(Account account);
public Account findAccountbyID(Integer id);
public List findAll();
public void transfer(String outUser,String inUser,Double moneny);
}
写出实现接口的类
package chapter04;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public class AccountDaoimpl implements AccountDao{
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Integer addaccount(Account account) {
String sql="insert into account(id,username,balance) values(?,?,?)";
Object[] params=new Object[]{account.getId(),account.getUsername(),account.getBalance()};
return jdbcTemplate.update(sql,params);
}
public Integer deleteAccount(Integer id) {
String sql="delete from account where id=?";
return jdbcTemplate.update(sql,id);
}
public Integer updateAccount(Account account) {
String sql="update account set username=?,balance=? where id=?";
Object[] params=new Object[]{account.getUsername(),account.getBalance(),account.getId()};
return jdbcTemplate.update(sql,params);
}
public Account findAccountbyID(Integer id) {
String sql="select * from account where id=?";
RowMapper accountRowMapper=new BeanPropertyRowMapper(Account.class);
Account account=jdbcTemplate.queryForObject(sql,accountRowMapper,id);
return account ;
}
public List findAll() {
String sql="select * from account";
RowMapper accountRowMapper=new BeanPropertyRowMapper(Account.class);
List accounts=jdbcTemplate.query(sql,accountRowMapper);
return accounts;
}
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)
@Override
public void transfer(String outUser, String inUser, Double moneny) {
//收款
jdbcTemplate.update("update account set balance= balance+? where username=?",moneny,inUser);
//模拟异常
int i=1/0;
//付款
jdbcTemplate.update("update account set balance= balance-? where username=?",moneny,outUser);
}
}
之后进行测试
package chapter04;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class AccountDaoimplTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext1.xml");
AccountDao accountDao = (AccountDao) ac.getBean("accountDao");
Account account = new Account();
account.setId(2);
account.setUsername("lucy");
account.setBalance(1100.0);
// Integer num =accountDao.addaccount(account);
// Integer num =accountDao.updateAccount(account);
// Integer num= accountDao.deleteAccount(1);
// if (num>0){
// System.out.println("插入成功");
// System.out.println(account.toString());
// }else {
// System.out.println("插入失败");
// }
// }
// Account account1= accountDao.findAccountbyID(2);
// System.out.println(account1);
List list=accountDao.findAll();
list.forEach(account1 -> {
System.out.println(account);
});
}
}
query():用于执行数据库的查询操作。常用的方法如下图所示:
//通过id查询
public Account findAccountById(int id);
//查询所有账户
public List findAllAccount();
//通过id查询账户数据信息
@Override
public Account findAccountById(int id) {
//定义sql语句
String sql = "select * from account where id =?";
//创建一个新的BeanPropertyRowMapper对象
RowMapper rowmapper = new BeanPropertyRowMapper(Account.class);
//将id绑定到sql语句中,并通过RowMapper返回一个Object类型的单行记录
return this.jdbctemplate.queryForObject(sql, rowmapper,id);
}
//查询所有账户信息
@Override
public List findAllAccount() {
//定义sql语句
String sql = "SELECT * FROM ACCOUNT";
//创建一个新的BeanPropertyRowMapper
RowMapper rowmapper = new BeanPropertyRowMapper(Account.class);
//执行静态的sql查询,并通过RowMapper返回结果
return this.jdbctemplate.query(sql,rowmapper);
}
并且在测试类中测试方法
@Test
public void run5(){
ApplicationContext applicationcontext = new ClassPathXmlApplicationContext("applicationcontext.xml");
AccountDao accountdao =(AccountDao) applicationcontext.getBean("accountdao");
Account account = accountdao.findAccountById(1);
System.out.println(account);
}
@Test
public void run6(){
ApplicationContext applicationcontext = new ClassPathXmlApplicationContext("applicationcontext.xml");
AccountDao accountdao =(AccountDao) applicationcontext.getBean("accountdao");
List account = accountdao.findAllAccount();
System.out.println(account);