利用springboot使用JdbcTemplate连接数据库
2017-06-02 00:00
771 查看
摘要: 跟着spring官网学习利用JdbcTemplate连接数据库
1.pom.xml文件配置
我们在pom文件里可以看到,com.h2database这个库起作用的范围是runtime,也就是说,当应用程序启动时,如果Spring Boot在classpath下检测到org.h2.Driver的存在,会自动配置H2数据库连接。现在启动应用程序来观察,以验证我们的想法。
2.实体类Customer.java文件
3.Application.java文件,为应用程序的入口文件,负责程序启动以及一些基础性的工作。
运行结果:
==============================================================================3.如果是自定义的数据库
pom.xml文件
连接生产数据库/src/main/resources/application.yml文件
1.pom.xml文件配置
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>jdbc</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <!--引入jdbc支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--引入嵌入式数据库支持h2,springboot提供自动配置的嵌入式数据库有h2,hsql,derby,即不需要提供任何连接配置就能使用--> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
我们在pom文件里可以看到,com.h2database这个库起作用的范围是runtime,也就是说,当应用程序启动时,如果Spring Boot在classpath下检测到org.h2.Driver的存在,会自动配置H2数据库连接。现在启动应用程序来观察,以验证我们的想法。
2.实体类Customer.java文件
package hello; /** * Created by guanguan on 17/6/1. */ 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); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
3.Application.java文件,为应用程序的入口文件,负责程序启动以及一些基础性的工作。
package hello; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.jdbc.core.JdbcTemplate; /** * Created by guanguan on 17/6/1. */ @SpringBootApplication public class Application implements CommandLineRunner{ private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class); } @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))"); List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream() .map(name -> name.split(" ")) .collect(Collectors.toList()); splitUpNames.forEach(name->log.info(String.format("Inserting customer record for %s,%s",name[0],name[1]))); 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())); } }
运行结果:
2017-06-02 10:40:54.671 INFO 13599 --- [ main] hello.Application : creating tables---1; 2017-06-02 10:40:54.845 INFO 13599 --- [ main] hello.Application : Inserting customer record for John,Woo 2017-06-02 10:40:54.845 INFO 13599 --- [ main] hello.Application : Inserting customer record for Jeff,Dean 2017-06-02 10:40:54.845 INFO 13599 --- [ main] hello.Application : Inserting customer record for Josh,Bloch 2017-06-02 10:40:54.845 INFO 13599 --- [ main] hello.Application : Inserting customer record for Josh,Long 2017-06-02 10:40:54.890 INFO 13599 --- [ main] hello.Application : Querying for customer records where first_name='Josh': 2017-06-02 10:40:54.896 INFO 13599 --- [ main] hello.Application : Customer[id=3,firstName='Josh',lastName='Bloch'] 2017-06-02 10:40:54.896 INFO 13599 --- [ main] hello.Application : Customer[id=4,firstName='Josh',lastName='Long'] 2017-06-02 10:40:54.898 INFO 13599 --- [ main] hello.Application : Started Application in 2.847 seconds (JVM running for 3.539) 2017-06-02 10:40:54.901 INFO 13599 --- [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f8f5f62: startup date [Fri Jun 02 10:40:52 CST 2017]; root of context hierarchy 2017-06-02 10:40:54.907 INFO 13599 --- [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown Process finished with exit code 0
==============================================================================3.如果是自定义的数据库
pom.xml文件
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
连接生产数据库/src/main/resources/application.yml文件
spring: datasource: url: jdbc:mysql://127.0.0.1/test username: root password: 123456 driverClassName: com.mysql.jdbc.Driver
相关文章推荐
- SpringBoot在利用JDBCTemplate连接数据库的时候报错 Incorrect column count: expected 1, actual 3] with root cause
- springboot使用JdbcTemplate完成对数据库的增删改查功能
- Spring Boot(6)— Spring Boot中使用JdbcTemplate访问数据库
- Spring Boot中使用JdbcTemplate访问数据库
- Spring Boot---(12)Spring Boot使用JdbcTemplate访问数据库
- 企业分布式微服务云SpringCloud SpringBoot mybatis (七)Spring Boot中使用JdbcTemplate访问数据库
- Spring Boot中使用JdbcTemplate访问数据库
- Spring Boot教程(二十九)使用JdbcTemplate操作数据库
- spring boot 教程(五)使用JdbcTemplate访问数据库
- (6)spring boot下使用jdbcTemplate操作数据库
- Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL
- 使用spring boot连接数据库出现no profiles are currently active的问题
- SpringBoot建立数据库连接JdbcTemplate和Mybatis两种方式
- SpringCloud SpringBoot mybatis 分布式微服务(八)Spring Boot中使用JdbcTemplate访问数据库
- Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL数据库的方法
- SpringBoot中连接MYSQL数据库,并使用JPA进行数据库的相关操作
- Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用
- Spring Boot中使用JdbcTemplate访问数据库
- SpringBoot使用JdbcTemplate操作数据库
- Spring Boot中使用JdbcTemplate访问数据库