Spring JdbcTemplate 的基本使用

Spring JdbcTemplate 的基本使用

一、Spring JdbcTemplate 的简介

它是spring框架中提供的一个对象,是对原始繁琐的jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型的数据Jdbc Template和Hibernate Template,操作nosql数据库的Redis Template,操作消息队列的JmsTemplate等。

二、JdbcTemplate开发步骤

1.导入Spring-jdbc和spring-tx坐标

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
 

2.创建数据库表和实体

创建数据库

创建实体

public class Student {
    private String username;
    private int password;
​
    public String getUsername() {
        return username;
    }
​
    public void setUsername(String username) {
        this.username = username;
    }
​
    public int getPassword() {
        return password;
    }
​
    public void setPassword(int password) {
        this.password = password;
    }
}

3.创建JdbcTemplate对象

Spring产生JdbcTemplate对象

我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将 数据源DataSource注入到JdbcTemplate模版对象中,配置如下:

<!--配置数据源DataSource-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///work"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>
    <!--配置jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--        必须使用数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

从容器中获得JdbcTemplate

ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
​
JdbcTemplate jdbcTemplate = (JdbcTemplate) app.getBean("jdbcTemplate");


4.执行数据库操作


public class Template {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate) app.getBean("jdbcTemplate");
        jdbcTemplate.update("insert into student values(?,?)","lisi",1234);
        System.out.println("插入数据成功");
    }

}

总结:

  1.  导入spring-jdbc和spring-tx坐标
  2. 创建数据库表和实体类
  3. 创建JdbcTemplate对象 
  4. 执行数据库操作

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值