就像单机Java应用程序一样,和数据库连接需要DataSource,然后生成到数据库的Connection再进行数据库操作
SpringBoot和原生的JDBC
先看SpringBoot项目源码
从上面看的出,SpringBoot只需要一个DataSource就可以完成数据库操作,JdbcTemplate只要封装数据库操作,已经由SpringBoot帮我们生成
项目结构
pom.xml加入了spring-boot-jdbc,mysql依赖
<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>test.demo</groupId> <artifactId>springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot</name> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.0.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> </project>
application.yml(里面就只有一个配置的用户信息)
user: properties: name: zzzz age: 18
源码下载地址
https://github.com/tangzhe7/springBootDemo
将数据库连接信息写进配置文件
修改application.yml就可以
user: properties: name: zzzz age: 18 spring: datasource: url: jdbc:mysql://localhost:3306/boot username: root password: 123456
源码下载
https://github.com/tangzhe7/springBootDemo/tree/master/springboot-jdbc-configuration-datasource