Spring Jdbc

Jdbc Template

  • spring中的jdbc模块负责数据库资源管理和错误处理,简化对数据库的操作,
  • Spring框架提供了Jdbc Template类,它是Spring框架数据抽象层的基础,其他更高层次的抽象类都是建立在它的基础之上,Jdbc Template 是 Spring Jdbc 的核心类。
    在这里插入图片描述

Spring 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">
    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--配置用户名-->
        <property name="username" value="root"/>
        <!--配置密码-->
        <property name="password" value="root"/>
        <!--连接数据库的URL-->
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <!--数据库驱动-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    </bean>
    <!--配置Jdbc Template模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--默认使用的数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置注入类-->
    <bean id="userDao" class="com.yzb.chapter04.example.UserDao">
        <!--配置JDBC模板-->
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
</beans>
  • username;数据库用户名
  • password:数据库的密码
  • url:数据库所在地址
  • driverClassName:数据库驱动名称

常用的方法

execute()

  • 主要用于创建数据库的表

代码

applicationContext.xml

<?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">
    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--配置用户名-->
        <property name="username" value="root"/>
        <!--配置密码-->
        <property name="password" value="root"/>
        <!--连接数据库的URL-->
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <!--数据库驱动-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    </bean>
    <!--配置Jdbc Template模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--默认使用的数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

JdbcTemplateTest

package com.yzb.chapter04.example1;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
/*
* 使用execute()方法进行创建表的工作
* */
public class JdbcTemplateTest {
    /*
    * 第一种方式
    * */
    public static void main(String[] args) {
        String path = "com/yzb/chapter04/example1/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);
        JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        //使用execute()方法执行SQL语句,创建用户账户管理表acount
        jdbcTemplate.execute("create table account("+
                "id int primary key auto_increment,"+
                "uesrname varchar(50),"+
                "balance double)");
        System.out.println("将建用户表account成功");
    }
    /*
    * 第二种方式:单元测试
    * */
    @Test
    public static void mainTest() {
        String path = "com/yzb/chapter04/example1/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);
        JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        //使用execute()方法执行SQL语句,创建用户账户管理表acount
        jdbcTemplate.execute("create table account("+
                "id int primary key auto_increment,"+
                "uesrname varchar(50),"+
                "balance double)");
        System.out.println("将建用户表account成功");
    }

}

update()

  • int update(String Sql) : 直接执行传入的sql语句,返回受影响的sql语句的行数;
  • int update(String sql ,Object … args): args设置sql中设置的参数,返回受影响的行数;
  • int update(String sql ,PreparedStatementSetter pss): 通过PreparedStatementSetter设置SQL语句中的参数,并返回受影响的行数;
  • int update(PreparedStatementCreator psc):用于执行从PreparedStatementCreator返回的语句,放回受影响的行数。

Account

package com.yzb.chapter04.example2;

public class Account {
    private Integer 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;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", balance=" + balance +
                '}';
    }
}

AccountDao

package com.yzb.chapter04.example2;

public interface AccountDao {
    //添加账户
    public int addAccount(Account account);
//    更改用户
    public  int updateAccount(Account account);
    //删除用户
    public int deleteAccount(int id );

}

AccountDaoImpl

package com.yzb.chapter04.example2;

import org.springframework.jdbc.core.JdbcTemplate;

public class AccountDaoImpl implements AccountDao {
    //声明JdbcTemplate属性以及setter方法
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //添加用户
    @Override
    public int addAccount(Account account) {
        //定义SQL
        String sql = "insert into account(username,balance) value(?,?)";
        //定义一个数组存储sql中的参数
        Object[] obj = {account.getUsername(),account.getBalance()};
        //执行添加操作,返回的是受sql语句影响的记录条数
        int update = jdbcTemplate.update(sql, obj);
        return update;
    }
    //更改用户
    @Override
    public int updateAccount(Account account) {
        //定义SQL
        String sql = "update account set username=?,balance=? where id=?";
        //定义一个数组存储sql中的参数
        Object[] obj = {account.getUsername(),account.getBalance(),account.getId()};
        //执行更改操作,返回的是受sql语句影响的记录条数
        int update = jdbcTemplate.update(sql, obj);
        return update;
    }
    //删除用户
    @Override
    public int deleteAccount(int id) {
    //定义sql
        String sql = "delete from account where id=?";
        //执行更改操作,返回的是受sql语句影响的记录条数
        int update = jdbcTemplate.update(sql, id);
        return update;
    }
}

applicationContext.xml

<?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">
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <!--配置用户名-->
    <property name="username" value="root"/>
    <!--配置密码-->
    <property name="password" value="root"/>
    <!--连接数据库的URL-->
    <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
    <!--数据库驱动-->
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
<!--配置Jdbc Template模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--默认使用的数据源-->
    <property name="dataSource" ref="dataSource"/>
</bean>
<!--配置注入类-->
<bean id="accountDao" class="com.yzb.chapter04.example2.AccountDaoImpl">
    <!--配置JDBC模板-->
    <property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
</beans>

UpdateTest

package com.yzb.chapter04.example2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UpdateTest {
    public static void main(String[] args) {
        //加载配置文件
        String path = "com/yzb/chapter04/example2/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);
        //获取AccountDao的实例
        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
        //创建Account的对象
        Account account = new Account();
        account.setUsername("tom");
        account.setBalance(1234.00);
        int num = accountDao.addAccount(account);
        if(num >0){
            System.out.println("成功插入了"+num+"条数据");
        }else {
            System.out.println("插入失败");
        }

    }
}

UpdateTest1

package com.yzb.chapter04.example2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UpdateTest1 {
    public static void main(String[] args) {
        //加载配置文件
        String path = "com/yzb/chapter04/example2/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);
        //获取AccountDao的实例
        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
        //创建Account的对象
        Account account = new Account();
        account.setUsername("tom");
        account.setId(1);
        account.setBalance(1234.00);
        int num = accountDao.updateAccount(account);
        if(num >0){
            System.out.println("成功修改了"+num+"条数据");
        }else {
            System.out.println("修改失败");
        }

    }
}

UpdateTest2

package com.yzb.chapter04.example2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UpdateTest2 {
    public static void main(String[] args) {
        //加载配置文件
        String path = "com/yzb/chapter04/example2/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);
        //获取AccountDao的实例
        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");

        int num = accountDao.deleteAccount(1);
        if(num >0){
            System.out.println("成功删除了"+num+"条数据");
        }else {
            System.out.println("删除失败");
        }

    }
}

query()

  • List query(String sql,RowMapper rowmapper):执行Spring类型提供的参数,并通过RowMapper(通过这个接口的实现类,在它的泛型中加入对应的JavaBean,括号里面加入javaBean.class)返回一个List类型的结果
  • RowMapper rowMapper = new BeanPropertyRowMapper(Account.class);
  • List query(String sql,Object[] args,RowMapper rowmapper):使用Object[]类似设置SQL语句中的参数,通过RowMapper的回调方法可以返回List类型的结果
  • queryForObject(String sql ,RowMapper rowmapper ,Object …args):将参数绑定到SQL语句中,并通过RowMapper返回一个Object类型的单行记录。
  • List Query(String sql ,PreparedStatementSetter pss,RowMapper rowmapper):根据提供的Spring类型的属性参数提供的SQL语句创建的PreparedStatement对象,并通过RowMapper返回一个List的结果集。
  • queryForList(String sql,Object[] args,class elementType):返回一个多行数据的结果。

代码

AccountDao

package com.yzb.chapter04.example2;

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();

}

UserDaoImpl

package com.yzb.chapter04.example2;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

public class AccountDaoImpl implements AccountDao {
    //声明JdbcTemplate属性以及setter方法
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //添加用户
    @Override
    public int addAccount(Account account) {
        //定义SQL
        String sql = "insert into account(username,balance) value(?,?)";
        //定义一个数组存储sql中的参数
        Object[] obj = {account.getUsername(),account.getBalance()};
        //执行添加操作,返回的是受sql语句影响的记录条数
        int update = jdbcTemplate.update(sql, obj);
        return update;
    }
    //更改用户
    @Override
    public int updateAccount(Account account) {
        //定义SQL
        String sql = "update account set username=?,balance=? where id=?";
        //定义一个数组存储sql中的参数
        Object[] obj = {account.getUsername(),account.getBalance(),account.getId()};
        //执行更改操作,返回的是受sql语句影响的记录条数
        int update = jdbcTemplate.update(sql, obj);
        return update;
    }
    //删除用户
    @Override
    public int deleteAccount(int id) {
    //定义sql
        String sql = "delete from account where id=?";
        //执行更改操作,返回的是受sql语句影响的记录条数
        int update = jdbcTemplate.update(sql, id);
        return update;
    }
    //通过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类型的单行记录
        Account account = this.jdbcTemplate.queryForObject(sql, rowMapper, id);
        return account;
    }
    //查询所有的账户信息
    @Override
    public List<Account> findAllAccount() {
        //定义sql语句
       String sql ="select * from account";
        //创建一个新的BeanPropertyRowMapper对象
       RowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
       //执行静态的sql语句查询,通过RowMapper返回结果
        List<Account> query = this.jdbcTemplate.query(sql, rowMapper);
        return query;
    }

}

UpdateTest3

package com.yzb.chapter04.example2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UpdateTest3 {
    public static void main(String[] args) {
        //加载配置文件
        String path = "com/yzb/chapter04/example2/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);
        //获取AccountDao的实例
        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
        Account accountById = accountDao.findAccountById(2);
        System.out.println(accountById);

    }
}

UpdatTest4

package com.yzb.chapter04.example2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class UpdateTest4 {
    public static void main(String[] args) {
        //加载配置文件
        String path = "com/yzb/chapter04/example2/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);
        //获取AccountDao的实例
        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
        List<Account> allAccount = accountDao.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }

    }
}

### Spring JDBC 使用教程 #### JdbcTemplate 类介绍 Spring框架简化了Java数据库连接(JDBC)编程,创建了一个名为`JdbcTemplate`的模板类 `org.springframework.jdbc.core.JdbcTemplate`[^2]。此模板类封装了许多繁琐的任务,比如资源获取和释放、异常处理以及执行SQL语句。 #### 配置 JdbcTemplate 实例 为了使用`JdbcTemplate`, 开发者需先定义一个数据源(`DataSource`)并将其注入到`JdbcTemplate`实例中: ```xml <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> ``` 这段XML配置文件片段展示了如何声明一个`JdbcTemplate` bean, 并通过属性设置关联的数据源对象[^1]。 #### 执行查询操作 利用`JdbcTemplate`可以方便地执行各种类型的SQL命令,包括但不限于SELECT查询: ```java List<Map<String, Object>> rows = jdbcTemplate.queryForList("SELECT * FROM users"); for (Map<String, Object> row : rows){ System.out.println(row); } ``` 上述代码演示了怎样调用`queryForList()`方法来运行一条简单的全表扫描查询,并打印每一行记录的结果集。 ### 常见问题解决方案 当遇到与Spring JDBC有关的问题时,可以从以下几个方面着手排查: - **无法找到驱动程序**: 如果应用程序抛出了类似于“找不到合适的Driver”的错误,则可能是由于缺少必要的JDBC驱动库造成的。确保已将相应的jar包加入classpath路径下。 - **事务管理失败**: 当尝试提交或回滚事务却未达到预期效果时,应检查是否正确设置了传播行为(propagation behavior),并且确认所有的DAO层方法都处于同一个事务上下文中工作[^3]. - **性能优化不足**: 对于大规模读取场景下的低效表现,考虑采用分页加载策略或者批量更新方式提升效率;另外还可以评估一下是否有更好的索引结构可用以加速特定模式下的检索速度[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值