一.添加 dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
二.配置JPA
server:
port: 80
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8
username: root
password: root #数据库名、用户名和密码改为自己的
type: com.alibaba.druid.pool.DruidDataSource
druid:
minIdle: 5 # 最小空闲连接数
initialSize: 5 # 初始化连接大小
maxActive: 5 # 最大连接数
stat-view-servlet:
login-username: admin
login-password: 123456
jpa:
database: MySQL
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
show-sql: true
hibernate:
ddl-auto: none
三.创建entity
1.创建entity package
2.配置数据源
3.生成entity
在entity package中会生成UserEntity.java文件,文件包括表名、字段、获取字段方法、设置字段方法等
package com.example.demo.entity;
import javax.persistence.*;
@Entity
@Table(name = "user", schema = "test", catalog = "")
public class UserEntity {
private int id;
private String name;
private String email;
@Id
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
if (id != that.id) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (email != null ? !email.equals(that.email) : that.email != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (email != null ? email.hashCode() : 0);
return result;
}
}
四.创建repository
1.创建repository package
2.创建IUserRepository.java
package com.example.demo.repository;
import com.example.demo.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface IUserRepository extends JpaRepository<UserEntity,Integer> {
}
五.创建路由并访问
package com.example.demo;
import com.example.demo.repository.IUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Demo1Application {
@Autowired
private IUserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
@GetMapping("/user")
public String user() {
// findById 接收主键值,1为数据库演示数据主键
return userRepository.findById(1).get().getEmail();
}
}