SpringBoot和數據庫連接


就像單機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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM