Spring boot 使用JdbcTemplate访问数据库

2025-05-29 0 57

springboot 是为了简化 spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物, 自动装配的特性让我们可以更好的关注业务本身而不是外部的xml配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 web 工程

spring framework 对数据库的操作在 jdbc 上面做了深层次的封装,通过 依赖注入 功能,可以将 datasource 注册到 jdbctemplate 之中,使我们可以轻易的完成对象关系映射,并有助于规避常见的错误,在 springboot 中我们可以很轻松的使用它。

特点

  • 速度快,对比其它的orm框架而言,jdbc的方式无异于是最快的
  • 配置简单, spring 自家出品,几乎没有额外配置
  • 学习成本低,毕竟 jdbc 是基础知识, jdbctemplate 更像是一个 dbutils

导入依赖

在 pom.xml 中添加对 jdbctemplate 的依赖

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
<!-- spring jdbc 的依赖包,使用 spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa 将会自动获得hikaricp依赖 -->

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-jdbc</artifactid>

</dependency>

<!-- mysql包 -->

<dependency>

<groupid>mysql</groupid>

<artifactid>mysql-connector-java</artifactid>

</dependency>

<!-- 默认就内嵌了tomcat 容器,如需要更换容器也极其简单-->

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-web</artifactid>

</dependency>

连接数据库

在 application.properties 中添加如下配置。值得注意的是,springboot默认会自动配置 datasource ,它将优先采用 hikaricp 连接池,如果没有该依赖的情况则选取 tomcat-jdbc ,如果前两者都不可用最后选取 commons dbcp2 。 通过 spring.datasource.type 属性可以指定其它种类的连接池

?

1

2

3

4

5

6

7

8
spring.datasource.url=jdbc:mysql://localhost:3306/chapter4?useunicode=true&characterencoding=utf-8&zerodatetimebehavior=converttonull&allowmultiqueries=true&usessl=false

spring.datasource.password=root

spring.datasource.username=root

#spring.datasource.type

#更多细微的配置可以通过下列前缀进行调整

#spring.datasource.hikari

#spring.datasource.tomcat

#spring.datasource.dbcp2

启动项目,通过日志,可以看到默认情况下注入的是 hikaridatasource

?

1

2

3

4
2018-05-07 10:33:54.021 info 9640 --- [ main] o.s.j.e.a.annotationmbeanexporter : bean with name 'datasource' has been autodetected for jmx exposure

2018-05-07 10:33:54.026 info 9640 --- [ main] o.s.j.e.a.annotationmbeanexporter : located mbean 'datasource': registering with jmx server as mbean [com.zaxxer.hikari:name=datasource,type=hikaridatasource]

2018-05-07 10:33:54.071 info 9640 --- [ main] o.s.b.w.embedded.tomcat.tomcatwebserver : tomcat started on port(s): 8080 (http) with context path ''

2018-05-07 10:33:54.075 info 9640 --- [ main] com.battcn.chapter4application : started chapter4application in 3.402 seconds (jvm running for 3.93)

具体编码

完成基本配置后,接下来进行具体的编码操作。 为了减少代码量,就不写 userdao 、 userservice 之类的接口了,将直接在 controller 中使用 jdbctemplate 进行访问数据库操作,这点是不规范的,各位别学我…

表结构

创建一张 t_user 的表

?

1

2

3

4

5

6
create table `t_user` (

`id` int(8) not null auto_increment comment '主键自增',

`username` varchar(50) not null comment '用户名',

`password` varchar(50) not null comment '密码',

primary key (`id`)

) engine=innodb default charset=utf8 comment='用户表';

实体类

?

1

2

3

4

5

6

7

8

9

10

11

12
package com.battcn.entity;

/**

* @author levin

* @since 2018/5/7 0007

*/

public class user {

private long id;

private string username;

private string password;

// todo 省略get set

}

restful 风格接口

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50
package com.battcn.controller;

import com.battcn.entity.user;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.jdbc.core.beanpropertyrowmapper;

import org.springframework.jdbc.core.jdbctemplate;

import org.springframework.web.bind.annotation.*;

import java.util.list;

/**

* @author levin

* @since 2018/4/23 0023

*/

@restcontroller

@requestmapping("/users")

public class springjdbccontroller {

private final jdbctemplate jdbctemplate;

@autowired

public springjdbccontroller(jdbctemplate jdbctemplate) {

this.jdbctemplate = jdbctemplate;

}

@getmapping

public list<user> queryusers() {

// 查询所有用户

string sql = "select * from t_user";

return jdbctemplate.query(sql, new object[]{}, new beanpropertyrowmapper<>(user.class));

}

@getmapping("/{id}")

public user getuser(@pathvariable long id) {

// 根据主键id查询

string sql = "select * from t_user where id = ?";

return jdbctemplate.queryforobject(sql, new object[]{id}, new beanpropertyrowmapper<>(user.class));

}

@deletemapping("/{id}")

public int deluser(@pathvariable long id) {

// 根据主键id删除用户信息

string sql = "delete from t_user where id = ?";

return jdbctemplate.update(sql, id);

}

@postmapping

public int adduser(@requestbody user user) {

// 添加用户

string sql = "insert into t_user(username, password) values(?, ?)";

return jdbctemplate.update(sql, user.getusername(), user.getpassword());

}

@putmapping("/{id}")

public int edituser(@pathvariable long id, @requestbody user user) {

// 根据主键id修改用户信息

string sql = "update t_user set username = ? ,password = ? where id = ?";

return jdbctemplate.update(sql, user.getusername(), user.getpassword(), id);

}

}

测试

由于上面的接口是 restful 风格的接口,添加和修改无法通过浏览器完成,所以需要我们自己编写 junit 或者使用 postman 之类的工具。

创建单元测试 chapter4applicationtests ,通过 testresttemplate 模拟 get 、 post 、 put 、 delete 等请求操作

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44
package com.battcn;

import com.battcn.entity.user;

import org.junit.test;

import org.junit.runner.runwith;

import org.slf4j.logger;

import org.slf4j.loggerfactory;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.boot.test.context.springboottest;

import org.springframework.boot.test.web.client.testresttemplate;

import org.springframework.boot.web.server.localserverport;

import org.springframework.core.parameterizedtypereference;

import org.springframework.http.httpmethod;

import org.springframework.http.responseentity;

import org.springframework.test.context.junit4.springrunner;

import java.util.list;

/**

* @author levin

*/

@runwith(springrunner.class)

@springboottest(classes = chapter4application.class, webenvironment = springboottest.webenvironment.random_port)

public class chapter4applicationtests {

private static final logger log = loggerfactory.getlogger(chapter4applicationtests.class);

@autowired

private testresttemplate template;

@localserverport

private int port;

@test

public void test1() throws exception {

template.postforentity("http://localhost:" + port + "/users", new user("user1", "pass1"), integer.class);

log.info("[添加用户成功]\\n");

// todo 如果是返回的集合,要用 exchange 而不是 getforentity ,后者需要自己强转类型

responseentity<list<user>> response2 = template.exchange("http://localhost:" + port + "/users", httpmethod.get, null, new parameterizedtypereference<list<user>>() {

});

final list<user> body = response2.getbody();

log.info("[查询所有] - [{}]\\n", body);

long userid = body.get(0).getid();

responseentity<user> response3 = template.getforentity("http://localhost:" + port + "/users/{id}", user.class, userid);

log.info("[主键查询] - [{}]\\n", response3.getbody());

template.put("http://localhost:" + port + "/users/{id}", new user("user11", "pass11"), userid);

log.info("[修改用户成功]\\n");

template.delete("http://localhost:" + port + "/users/{id}", userid);

log.info("[删除用户成功]");

}

}

总结

本章介绍了 jdbctemplate 常用的几种操作,详细请参考 jdbctemplate api文档

目前很多大佬都写过关于 springboot 的教程了,如有雷同,请多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.release 编写,包括新版本的特性都会一起介绍…

原文链接:http://blog.battcn.com/2018/05/07/springboot/v2-orm-jdbc

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring boot 使用JdbcTemplate访问数据库 https://www.kuaiidc.com/111777.html

相关文章

发表评论
暂无评论