Spring jdbc数据库管理

Spring JDBC模块负责数据库资源管理,针对数据库操作,Spring框架提供了JdbcTemplate类,该类是Spring JDBC的核心类。

一、Spring JDBC的配置

Spring JDBC主要由4个包组成:

 Spring对数据库的操作都封装在了这几个包中,想要使用JDBC就需要对其进行配置,在Spring容器中,对JDBC的配置是在applicationContext.xml文件中进行的。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
    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/context 
        	http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop 
        	http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx 
        	http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	
	<!-- 1.配置数据源(连接池) -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!-- 数据库驱动 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<!-- 连接数据库的url -->
		<property name="url" value="jdbc:mysql://localhost:3306/spring?"></property>
		<!-- 连接数据库的用户名 -->
		<property name="username" value="root"></property>
		<!-- 连接数据库的密码 -->
		<property name="password" value="123456"></property>
	</bean>
	<!-- 2.配置jdbc模板 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<!-- 默认必须使用数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- 3.配置注入类 -->
	<bean id="***" class="***">
		<!-- 将jdbcTemplate注入到实例中 -->
		<property name="jdbctemplate" ref="jdbcTemplate"></property>
	</bean>
</beans>

 对于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表创建成功");

    }


}

之后数据表被增加成功

2.update():用于执行插入,更新和删除操作。

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<Account> 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<Account> accountRowMapper=new BeanPropertyRowMapper<Account>(Account.class);
        Account account=jdbcTemplate.queryForObject(sql,accountRowMapper,id);
        return account ;
    }

    public List<Account> findAll() {
        String sql="select * from account";
        RowMapper<Account> accountRowMapper=new BeanPropertyRowMapper<Account>(Account.class);
        List<Account> 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<Account> list=accountDao.findAll();
        list.forEach(account1 -> {
            System.out.println(account);
        });
    }
}

3.query():用于执行数据库查询操作。

query():用于执行数据库的查询操作。常用的方法如下图所示:

//通过id查询
	public Account findAccountById(int id);
	//查询所有账户
	public List<Account> findAllAccount(); 

//通过id查询账户数据信息
	@Override
	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);
	}
	//查询所有账户信息
	@Override
	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);
	}

并且在测试类中测试方法

@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> account = accountdao.findAllAccount();
		System.out.println(account);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值