前提: 項目已經(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ù).