创建项目
导入jar包 mysql 数据库和连接池jar
代码语言:javascript复制<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
application.peoperties
代码语言:javascript复制spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&autoReconnectForPools=true
# JPA 配置
# 数据库为 MySQL
spring.jpa.database=mysql
# 在控制台打印 SQL
spring.jpa.show-sql=true
# 数据库平台
spring.jpa.database-platform=mysql
# 每次启动项目时,数据库初始化策略
spring.jpa.hibernate.ddl-auto=update
# 指定默认的存储引擎为 InnoDB ,否则默认情况下,自动创建表的时候会使用 MyISAM 作为表的存储引擎
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
创建model类
代码语言:javascript复制import javax.persistence.*;
import java.util.Objects;
/**
* https://blog.csdn.net/mononoke111/article/details/91924002
*/
@Entity
@Table(name = "tb_score", schema = "mydb", catalog = "")
public class TbScoreEntity {
private int id;
private String userid;
private String subject;
private Double score;
@Id
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "userid")
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
@Basic
@Column(name = "subject")
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@Basic
@Column(name = "score")
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TbScoreEntity that = (TbScoreEntity) o;
return id == that.id && Objects.equals(userid, that.userid) && Objects.equals(subject, that.subject) && Objects.equals(score, that.score);
}
@Override
public int hashCode() {
return Objects.hash(id, userid, subject, score);
}
}
创建dao类
代码语言:javascript复制package com.example.jpa.demojpa.dao;
import com.example.jpa.demojpa.entity.TbScoreEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(path = "score")
public interface ScoreDao extends JpaRepository<TbScoreEntity, Integer> {
}
postman请求,可以进行GET POST PUT PATCH DELETE请求 http://localhost:8080/ http://localhost:8080/score/1