SpringBoot 添加數(shù)據(jù)庫的支持

前提: 項目已經(jīng)配置好能通過URL獲取靜態(tài)數(shù)據(jù) + mysql 數(shù)據(jù)庫已經(jīng)搭建好并且機器上面可以訪問

參考Spring Boot官網(wǎng):?https://spring.io/guides/gs/accessing-data-mysql/

Step1: pom.xml添加包依賴

<dependency>

????<groupId>org.springframework.boot</groupId>

????<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

? ? <groupId>mysql</groupId>

? ? <artifactId>mysql-connector-java</artifactId>

? ? <scope>runtime</scope>

</dependency>

Step2: 創(chuàng)建?src/main/resources/application.properties, 添加如下內(nèi)容

spring.jpa.hibernate.ddl-auto=none

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

spring.datasource.username=springuser [注意,user這里不要用引號]

spring.datasource.password=ThePassword [注意, password這里不要用引號]

Step3: 創(chuàng)建 @Entity 實體?src/main/java/hello/User.java(用戶根據(jù)自己的需求來新建文件)? (ORM層, 用于映射數(shù)據(jù)庫字段)

package hello;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class

public class User {?

?????@Id?

?????@GeneratedValue(strategy=GenerationType.AUTO)?

?????private Integer id;?

?????private String name; priv

? ? ?public Integer getId() { return id; }

????public void setId(Integer id) { this.id = id; }?

?}

Step4: 創(chuàng)建倉庫(訪問DB層)

package hello;

import hello.User;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

@Repository

public interface UserRepository extends JpaRepository<User, Long> {

}

Step5: controller 層訪問數(shù)據(jù)

........

@RestController

public List<User> index() {

????return userService.findAll();

}

.........

經(jīng)測試, 可以輸出數(shù)據(jù).

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容