清茶书香

一杯清茶,一本书籍,一个下午。


  • 首页

  • 归档

  • 分类

  • 关于

  • 搜索
Redis JPA Solr SpringData SpringMVC localRepository local Mapper 事务 Mybatis JDBC AOP DI IOC 常用函数 触发器 存储过程 Promise Gateway SpringCloud vue-cli axios es6 webpack npm vue 个性化 zsh 终端 caffeine jvm缓存 guava cache validation Mapping MapStruct comment 小程序 建站 WeHalo config logback plugins database idea maven spring https http nginx password RabbitMQ 秒杀系统 Windows MySQL 数据备份 halo SpringBoot shell Linux ip Optional Stream Lambda k8s Docker 列编辑 vim MacOS 图片合成 Java 远程联调 nps 内网穿透

Spring框架之JDBC

发表于 2019-06-22 | 分类于 spring系列 | 0 | 阅读次数 200

概述

在Spring JDBC模块中,所有的类可以被分到四个单独的包:

  1. core
    即核心包,它包含了JDBC的核心功能。此包内有很多重要的类,包括:JdbcTemplate类、SimpleJdbcInsert类,SimpleJdbcCall类,以及NamedParameterJdbcTemplate类。

  2. datasource
    即数据源包,访问数据源的实用工具类。它有多种数据源的实现,可以在JavaEE容器外部测试JDBC代码。

  3. object
    即对象包,以面向对象的方式访问数据库。它允许执行查询并返回结果作为业务对象。它可以在数据表的列和业务对象的属性之间映射查询结果。

  4. support
    即支持包,是core包和object包的支持类。例如提供了异常转换功能的SQLException类。

添加依赖

要想使用spring的依赖和Spring JDBC依赖

<!-- spring IOC最小依赖,maven可以自动将其他依赖添加进来 -->
<dependency>
	<groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<!-- spring JDBC的依赖库 -->
<dependency>
    <groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>

配置数据源

首先要有关于数据库连接的属性配置文件

jdbc.url=jdbc:mysql://localhost:3306/books
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
jdbc.characterEncoding=utf8

实体类

@Setter
@Getter// 生成getter、setter的注解(需要Lombok插件)
public class BookType {
    private Integer id;// 图书类型id
    private String tname;// 图书类型
}

XML配置

<!-- 配置数据源 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="connectionProperties">
            <props>
                <prop key="charsetEncoding">${jdbc.characterEncoding}</prop>
            </props>
        </property>
    </bean>

Annotation配置

/**
* @program: spring
*
* @description: 用注解的方式配置数据源
*
* @author: Bennett
*
* @create: 2019-06-20 15:11
*
* @version: 1.0
**/

@PropertySource("classpath:jdbc.properties")
@Component
public class MyDataSource extends DriverManagerDataSource {

    public MyDataSource(@Value("${jdbc.driver}") String driver, @Value("${jdbc.url}") String url, @Value("${jdbc.user}")
            String username, @Value("${jdbc.password}") String password, @Value("${jdbc.characterEncoding}") String characterEncoding){
        super.setDriverClassName(driver);
        super.setUrl(url);
        super.setUsername(username);
        super.setPassword(password);
        Properties properties = new Properties();
        properties.setProperty("characterEncoding",characterEncoding);
        super.setConnectionProperties(properties);
    }
}

JdbcTemplate

JdbcTemplate其实就是一个操作数据库的工具类,它提供了一系列的关于操作数据库的方法,比如常用的增删改查等。它的使用方式和apache提供的Dbutils工具库相似,只是类名不同而已。下面给出示例

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
// 查询方法
jdbcTemplate.query("select * from booktype",new BeanPropertyRowMapper<BookType>(BookType.class));
// 增加、删除、修改方法()
jdbcTemplate.update("insert into booktype (tname) values (?)",bookType.getTname());
/**
*此处只给出了增加的方法,删除、修改只需要换了SQL语句即可
*jdbcTemplate只是封装了PrepareStatement的方法,用的还是占位符配合参数的方式
**/

JdbcTemplate提供的方法:

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
  • query方法及queryForXXX方法:用于执行查询相关语句;
  • call方法:用于执行存储过程、函数相关语句。

JdbcTemplate的查询方法

查询单个数据

一般使用queryForObject(String sql, Object[] args, Class<T> requiredType)方法

String sql = "select tname from booktype where id = ?";
String tName = JdbcTemplate().queryForObject(sql, new Object[] { bookType.getId() }, String.class);

查询多行数据

使用query方法,但要传入一个BeanPropertyRowMapper对象参数。这种事自动映射的方式,但是要求你的实体类的属性名和你建的表的字段名一一对应(不对应就需要将你的查询结果的列名起别名为你的实体类的属性名)

// 如果双方名字不对应,则String sql = "select tname as tName from booktype"
List<BookType> bookTypeList = jdbcTemplate.query("select * from booktype",new BeanPropertyRowMapper<BookType>(BookType.class));
// query方法中的第三个参数如果SQL语句没有条件判断就不需要了

NamedParameterJdbcTemplate

在经典的 JDBC 用法中, SQL 参数是用占位符 ? 表示,并且受到位置的限制。定位参数的问题在于, 一旦参数的顺序发生变化, 就必须改变参数绑定。
在 Spring JDBC 框架中, 绑定 SQL 参数的另一种选择是使用具名参数(named parameter)。

什么是具名参数

具名参数: SQL 按名称(以冒号开头)而不是按位置进行指定. 具名参数更易于维护, 也提升了可读性. 具名参数由框架类在运行时用占位符取代
具名参数只在 NamedParameterJdbcTemplate 中得到支持。NamedParameterJdbcTemplate可以使用全部jdbcTemplate方法。

具名参数使用示例

获取新增的主键:
NamedParameterJdbcTemplate还新增了KeyHolder类,使用它我们可以获得主键,类似Mybatis中的useGeneratedKeys。

@Test
public void testNamedParameter(){
    NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(dataSource);
    String sql = "insert into booktype (id,tname) values (:id,:tname)";
    BookType bt = new BookType();
    bt.setId(66);
    bt.setTname("test");
    SqlParameterSource sqlParameterSource=new BeanPropertySqlParameterSource(bt);
    npjt.update(sql,sqlParameterSource);
    //KeyHolder keyHolder = new GeneratedKeyHolder();
    //npjt.update(sql, sqlParameterSource, keyHolder);
    // 插入成功后,返回该条信息的主键id
    //int resultId = keyHolder.getKey().intValue();
    //System.out.println(resultId);
}

Spring Jdbc还提供了很多种类,比如调用存储过程或者存储函数的SimpleJdbcCall等,这里就不再赘述了。Spring JDBC提供的类也依旧只是适合查单张表使用,涉及联表查询就还是需要Hibernate、Mybatis等数据库框架才能处理的更加完美。

Bennett wechat
欢迎收藏我的微信小程序,方便查看更新的文章。
  • 本文作者: Bennett
  • 本文链接: https://hibennett.cn/archives/spring-jdbc
  • 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!
# spring # JDBC
spring Core之AOP
Mybatis详解(一)
  • 文章目录
  • 站点概览
Bennett

Bennett

60 日志
28 分类
74 标签
RSS
Github E-mail Gitee QQ
Creative Commons
Links
  • MacWk
  • 知了
0%
© 2020 — 2023 hibennett.cn版权所有
由 Halo 强力驱动
|
主题 - NexT.Pisces v5.1.4

浙公网安备 33010802011246号

    |    浙ICP备2020040857号-1