前提: 项目已经配置好能通过URL获取静态数据 + mysql 数据库已经搭建好并且机器上面可以访问
参考Spring Boot官网: https://spring.io/guides/gs/accessing-data-mysql/
Step1: pom.xml添加包依赖
Step2: 创建 src/main/resources/application.properties, 添加如下内容
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: 创建 @Entity 实体 src/main/java/hello/User.java(用户根据自己的需求来新建文件) (ORM层, 用于映射数据库字段)
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: 创建仓库(访问DB层)
package hello;
import hello.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository
}
Step5: controller 层访问数据
........
@RestController
public List
return userService.findAll();
}
.........
经测试, 可以输出数据.