spring框架中jdbsTemplate的简介及使用

简介:

        

        1.JdbcTemplate是Spring框架对JDBC的封装,这让使用JDBC更简单,更加方便。

        2.JdbcTemplate是Spring的一部分。他帮助我们避免一些常见的错误,比如忘了关闭连         接。

        3.我们只需要提供SQL语句并获取结果即可。


(一):创建一个数据库

在这里我用的是navicat软件建了一个名为springjdbc数据库,并添加了一个user表

加入初始数据


(二):XML文件配置和依赖导入

2.1 依赖导入

在pom文件中


<dependencies>
<!--        jdbc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.2</version>
        </dependency>
<!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
<!--        引入德鲁伊连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.15</version>
        </dependency>
</dependencies>

2.2 XML文件配置

        环境准备:要使用它提供的功能就先创建一个jdbcTemplate对象,在xml文件中配置

        

在spring.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.xsd">

<!--    引入德鲁伊连接池,在这里我使用的时阿里提供的连接池,你也可以自己写一个,主要目的就是为了获取和数据库的连接-->
        <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="url" value="jdbc:mysql://localhost:3306/springjdbc"/>
            <property name="username" value="root"/>
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <property name="password" value="WJH5201314"/>
        </bean>

<!--    配置jdbcTemplate对象,并为其注入上面配置的连接池-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="ds"/>
</bean>

</beans>

(三):创建一个user类用于需要时接受数据库的数据

就写了三个属性和其get,set方法还有toString,包括一个有参构造和无参构造

public class user {
    private Integer id;
    private String realName;
    private Integer age;

    @Override
    public String toString() {
        return "user{" +
                "id=" + id +
                ", realName='" + realName + '\'' +
                ", age=" + age +
                '}';
    }

    public user() {
    }

    public user(Integer id, String reaName, Integer age) {
        this.id = id;
        this.realName = reaName;
        this.age = age;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}

(四):使用jdbcTemplate 

4.1插入

    public void testInsert() {
        //解析xml文件将对象存储在map集合中
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

        //从map集合中取出jdbcTemplate对象
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);

        //准备一个sql语句
        String sql = "insert into user(id,real_name,age)values(?,?,?)";

        //调用update方法进行插入
        int count = jdbcTemplate.update(sql,4,"小王",18);

        //输出结果
        System.out.println(count)
    }

4.2删

 public void testDelete() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "delete from user where id=?";
        int count = jdbcTemplate.update(sql,4);
        System.out.println(count);
    }

4.3改

  public void testUpdate() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "update user set real_name=?,age=? where id=?";
        int count = jdbcTemplate.update(sql, "张三丰", 55, 2);
        System.out.println(count);
    }

4.4查

public void testQueryOne() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "select * from user where id=?";
        
        //第二个参数将查询的结果映射到刚刚你准备的user类中并返回一个user对象
        user user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(user.class), 2);

        //查看结果
        System.out.println(user);
    }

运行结果:
 

4.5批量查

    public void testQueryAll() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "select * from user";

        //使用的是query方法,依然映射带user中,返回一个列表
        List<user> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(user.class));
        
System.out.println(list);
    }

运行结果

4.6批量加

 public void testBatchInsert() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "insert into user(id,real_name,age) values(?,?,?)";

        //准备数据
        Object[] obj1 = {5,"小花",30};
        Object[] obj2 = {6,"小明",3};
        Object[] obj3 = {7,"小张",130};

        //将准备的数据添加到list集合中
        List<Object[]> list = new ArrayList<Object[]>();
        list.add(obj1);
        list.add(obj2);
        list.add(obj3);

        //执行jdbc的batchUpdate方法,会对list集合中的元素依次添加,返回一个数组
        int[] ints = jdbcTemplate.batchUpdate(sql, list);

        //接受执行成功的条数
        System.out.println(ints.length);
    }

 4.7批量删除

 public void testBatchDelete() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "delete from user where id=?";
        Object[] obj1 = {5};
        Object[] obj2 = {6};
        Object[] obj3 = {7};
        List<Object[]> list = new ArrayList<Object[]>();
        list.add(obj1);
        list.add(obj2);
        list.add(obj3);
        int[] ints = jdbcTemplate.batchUpdate(sql, list);
        System.out.println(ints[0]);
    }

4.8回调函数,jdbc代码

如果你还是想写原来的jdbc代码可以调用回调函数

    public void testCallBack() {
        //如果你想写jdbc代码就可以用callback回调函数
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "select * from user where id=?";
      
        //当execute方法执行时,doInPrepareStatement方法执行
        user user = jdbcTemplate.execute(sql, new PreparedStatementCallback<user>() {
            @Override
            public user doInPreparedStatement(PreparedStatement ps) throws SQLException,         DataAccessException {
                //创建user对象用于接受值
                user user = new user();

                //意思是在传进来的sql语句中第一个问号的值为4
                ps.setInt(1, 4);

                //接收查询结果
                ResultSet resultSet = ps.executeQuery();

                if (resultSet.next()) {
                    
                    //获取查询到的信息
                    int id = resultSet.getInt("id");
                    String realName = resultSet.getString("real_name");
                    int age = resultSet.getInt("age");

                    //赋值到user属性中
                    user.setId(id);
                    user.setRealName(realName);
                    user.setAge(age);
                }
                //返回user
                return user;
            }
        });
        System.out.println(execute);
    }
}

(五)注意

                1.jdbcTemplate在增删改用的方法都是update,查单条用的queryForObject方法,查多条

                   方法用query方法

                2.在批量查那一部分,real_name映射到user对象时,user对象中的方法必须为

                    setRealName()才能映射成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值