好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring Boot如何使用JDBC获取相关的数据详解

什么是jdbc

java database connectivity 是一种用于执行sql语句的java api,与数据库建立连接、发送 操作数据库的语句并处理结果。

spring boot 使用 jdbc

增加依赖

修改pom.xml:将dependecies 修改为如下两个

?

1

2

3

4

5

6

7

8

9

10

<dependencies>

  <dependency>

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

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

  </dependency>

  <dependency>

   <groupid>com.h2database</groupid>

   <artifactid>h2</artifactid>

  </dependency>

  </dependencies>

创建 customer.java 类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package com.example.kane.model;

 

public class customer {

  private long id;

  private string firstname, lastname;

 

  public customer( long id, string firstname, string lastname) {

  this .id = id;

  this .firstname = firstname;

  this .lastname = lastname;

  }

 

  @override

  public string tostring() {

  return string.format(

   "customer[id=%d, firstname='%s', lastname='%s']" ,

   id, firstname, lastname);

  }

 

  // getters & setters omitted for brevity

}

修改application 类

?

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

51

52

53

54

55

56

57

58

59

60

61

package com.example.kane;

 

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

import org.springframework.boot测试数据mandlinerunner;

import org.springframework.boot.springapplication;

import org.springframework.boot.autoconfigure.springbootapplication;

import org.springframework.boot.web.client.resttemplatebuilder;

import org.springframework.context.annotation.bean;

import org.springframework.jdbc.core.jdbctemplate;

import org.springframework.scheduling.annotation.enablescheduling;

 

import java.util.arrays;

import java.util.list;

import java.util.stream.collectors;

 

import org.slf4j.logger;

import org.slf4j.loggerfactory;

import org.springframework.web.client.resttemplate;

 

import com.example.kane.model.customer;

 

@springbootapplication

//@enablescheduling

public class restfulwebservice1application implements commandlinerunner{

 

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

 

  public static void main(string args[]) {

  springapplication.run(restfulwebservice1application. class , args);

  }

 

  @autowired

  jdbctemplate jdbctemplate;

 

  @override

  public void run(string... strings) throws exception {

 

  log.info( "creating tables" );

 

  jdbctemplate.execute( "drop table customers if exists" );

  jdbctemplate.execute( "create table customers(" +

   "id serial, first_name varchar(255), last_name varchar(255))" );

 

  // split up the array of whole names into an array of first/last names

  list<object[]> splitupnames = arrays.aslist( "john woo" , "jeff dean" , "josh bloch" , "josh long" ).stream()

   .map(name -> name.split( " " ))

   .collect(collectors.tolist());

 

  // use a java 8 stream to print out each tuple of the list

  splitupnames.foreach(name -> log.info(string.format( "inserting customer record for %s %s" , name[ 0 ], name[ 1 ])));

 

  // uses jdbctemplate's batchupdate operation to bulk load data

  jdbctemplate.batchupdate( "insert into customers(first_name, last_name) values (?,?)" , splitupnames);

 

  log.info( "querying for customer records where first_name = 'josh':" );

  jdbctemplate.query(

   "select id, first_name, last_name from customers where first_name = ?" , new object[] { "josh" },

   (rs, rownum) -> new customer(rs.getlong( "id" ), rs.getstring( "first_name" ), rs.getstring( "last_name" ))

  ).foreach(customer -> log.info(customer.tostring()));

  }

}

运行项目看结果

2019-03-01 14:19:52.078  info 7436 --- [  restartedmain] c.e.kane.restfulwebservice1application   : creating tables
2019-03-01 14:19:52.086  info 7436 --- [  restartedmain] com.zaxxer.hikari.hikaridatasource       : hikaripool-1 - starting...
2019-03-01 14:19:52.392  info 7436 --- [  restartedmain] com.zaxxer.hikari.hikaridatasource       : hikaripool-1 - start completed.
2019-03-01 14:19:52.429  info 7436 --- [  restartedmain] c.e.kane.restfulwebservice1application   : inserting customer record for john woo
2019-03-01 14:19:52.430  info 7436 --- [  restartedmain] c.e.kane.restfulwebservice1application   : inserting customer record for jeff dean
2019-03-01 14:19:52.430  info 7436 --- [  restartedmain] c.e.kane.restfulwebservice1application   : inserting customer record for josh bloch
2019-03-01 14:19:52.430  info 7436 --- [  restartedmain] c.e.kane.restfulwebservice1application   : inserting customer record for josh long
2019-03-01 14:19:52.461  info 7436 --- [  restartedmain] c.e.kane.restfulwebservice1application   : querying for customer records where first_name = 'josh':
2019-03-01 14:19:52.480  info 7436 --- [  restartedmain] c.e.kane.restfulwebservice1application   : customer[id=3, firstname='josh', lastname='bloch']
2019-03-01 14:19:52.480  info 7436 --- [  restartedmain] c.e.kane.restfulwebservice1application   : customer[id=4, firstname='josh', lastname='long']
2019-03-01 14:20:01.122  info 7436 --- [nio-8080-exec-5] o.a.c.c.c.[tomcat].[localhost].[/]       : initializing spring dispatcherservlet 'dispatcherservlet'
2019-03-01 14:20:01.123  info 7436 --- [nio-8080-exec-5] o.s.web.servlet.dispatcherservlet        : initializing servlet 'dispatcherservlet'
2019-03-01 14:20:01.146  info 7436 --- [nio-8080-exec-5] o.s.web.servlet.dispatcherservlet        : completed initialization in 22 ms

说明

官网的例子,没有配置jdbc template的datasource,默认使用的是h2 的内存存储的数据库,只能当做测试使用。下面会有介绍更改datasource的方法

介绍下 commandlinerunner

功能

在项目启动后,执行执行功能,我们可以定一个类,去实现commandlinerunner接口,重写run方法,执行一部分操作。需要注意的是,定义类必须标记为spring管理的组件

测试类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package com.example.kane.model;

 

import org.springframework.boot测试数据mandlinerunner;

import org.springframework.core.annotation.order;

import org.springframework.stereotype测试数据ponent;

@component

@order (value= 1 ) //因为可能有许多事情要做,order 可以根据大小,判读执行的顺序

public class run_after_application implements commandlinerunner{

 

  @override

  public void run(string... args) throws exception {

  // todo auto-generated method stub

  system.out.println( "-----------------------" );

  }

 

}

介绍下jdbctempalte

在jdbc核心包中,jdbctemplate是主要的类,简化了jdbc的使用,避免了一些常规错误。它能够执行jdbc核心流程,在应用代码之上提供sql语句、导出结果。这个类执行sql查询、更新、对结果集重复操作捕获jdbc的异常。并将它翻译成org.springframework.dao 包中定义的基本的、信息量更大的异常层次结构。

jdbc构造方法

jdbctemplate()

?

1

2

//为bean创建一个jdbctemplate以供使用

//再没配置datasource的情况下 springboot提供了 一些嵌入式的数据库支持,上面的例子使用的就是h2数据库,是一个内存的数据库

jdbctemplate(javax.sql.datasource datasource)

?

1

2

//构造的时候传入一个 datasource,来获取链接

//jdbctemplate spring boot默认链接的是h2 database,

在spring boot中配置mysql 数据库

数据库配置类 db_config

?

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

package com.example.kane.config;

 

import org.apache测试数据mons.dbcp.basicdatasource;

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

import org.springframework.context.annotation.bean;

import org.springframework.context.annotation.configuration;

import javax.sql.datasource;

@configuration

public class db_config {

  //这个类是一个config类

  @value ( "${db.driver}" )

  private string driver;

 

  @value ( "${db.password}" )

  private string password;

 

  @value ( "${db.url}" )

  private string url;

 

  @value ( "${db.username}" )

  private string username;

  @bean

  public datasource datasource1() {

   basicdatasource datasource = new basicdatasource();

   datasource.setdriverclassname(driver);

   datasource.seturl(url);

   datasource.setusername(username);

   datasource.setpassword(password);

   return datasource;

  }

}

application.properties

?

1

2

3

4

5

6

# database

# mysqljdbc连接驱动

db.driver:com.mysql.cj.jdbc.driver

db.url:jdbc:mysql: //localhost:3306/test

db.username:root

db.password:root

pom.xml

?

1

2

3

4

5

6

7

8

9

10

11

<dependency>

  <groupid>commons-dbcp</groupid>

  <artifactid>commons-dbcp</artifactid>

  <version> 1.4 </version>

</dependency>

<dependency>

  <groupid>mysql</groupid>

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

  <scope>runtime</scope>

</dependency>

<!-- 需要用到commons-dbcp连接池,以及连接mysql使用的drver-->

application 启动类修改

?

1

2

3

4

5

@autowired

jdbctemplate jdbctemplate;

//下面是加载了数据库的配置。只需要增加这个

@autowired

db_config db_config;

运行程序后会发现数据存储到本地数据库

?

1

2

3

4

5

6

select * from customers;

------------------------

1 john woo

2 jeff dean

3 josh bloch

4 josh long

另一个简单的方法配置mysql数据库

直接修改application.properties

?

1

2

3

4

5

# database

spring.datasource.url=jdbc:mysql: //localhost:3306/test

spring.datasource.username=root

spring.datasource.password=

spring.datasource.driver- class -name=com.mysql.cj.jdbc.driver

将properties改成yml文件 application.yml

?

1

2

3

4

5

6

spring:

  datasource:

  url: jdbc:mysql: //localhost:3306/test

  username: root

  password: root

  driver- class -name: com.mysql.cj.jdbc.driver

注:这两种方式又回归到配置文件的方式了,

jdbc template常用方法

execute方法:可以用于执行任何sql语句,一般用于执行ddl语句; update方法及batchupdate方法:update方法用于执行新增、修改、删除等语句;batchupdate方法用于执行批处理相关语句; query方法及queryforxxx方法:用于执行查询相关语句; call方法:用于执行存储过程、函数相关语句。 参考官网 https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/jdbctemplate.html

关于连接池的一些内容

为什么要使用数据库连接池?

因为建立数据库连接是一个非常耗时的过程,使用连接池可以预先同数据库建立连接,放在内存中。应用需要使用数据库的时候直接使用连接池中的连接即可。

当前三大主流连接池

dbcp:提供最大空闲连接数,超过连接全部自动断开连接,其他两个没有。 c3p0:提供最大空闲连接时间,这样可以做到自动收回空闲连接的机制 druid:阿里出品的,同样提供最大的空闲连接时间

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

原文链接:https://HdhCmsTestcnblogs测试数据/primadonna/p/10470472.html

查看更多关于Spring Boot如何使用JDBC获取相关的数据详解的详细内容...

  阅读:17次