1、创建项目
添加Spring Data JPA和Rest Repositories
2、添加MySQL依赖并设置上下文路径、数据源信息
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
server.servlet.context-path=/api
###
##数据源信息配置
###
#数据库地址
spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?serverTimezone=UTC&characterEncoding=utf8
#数据库用户名
spring.datasource.username=root
#数据库密码
spring.datasource.password=123456
#数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
####
#JPA持久化配置
####
#指定数据库类型
spring.jpa.database=MYSQL
#指定是否在日志中显示SQL语句
spring.jpa.show-sql=true
#指定自动创建、更新数据库表等配置,update表示如果数据库中存在持久化类对应的表就不创建,不存在就创建对应的表
spring.jpa.hibernate.ddl-auto=update
#让控制器输出的JSON字符串格式更美观
spring.jackson.serialization.indent-output=true
3、创建实体类Student
package com.yzh.rest.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student_table")
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;//主键
private String sno;
private String sname;
private String ssex;
}
4、创建数据访问层StudentRepository
package com.yzh.rest.repository;
import java.util.List;
import com.yzh.rest.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RestResource;
public interface StudentRepository extends JpaRepository<Student, Integer>{
/**
* 自定义接口查询方法,暴露为REST资源
*/
@RestResource(path = "snameStartsWith", rel = "snameStartsWith")
List<Student> findBySnameStartsWith(@Param("sname") String sname);
}
5、测试
此处我用的是ApiPost客户端进行测试
{
"_embedded": {
"students": [
{
"sno": "36",
"sname": "barret",
"ssex": "男",
"_links": {
"self": {
"href": "http://localhost:8080/api/students/1"
},
"student": {
"href": "http://localhost:8080/api/students/1"
}
}
},
{
"sno": "25",
"sname": "marry",
"ssex": "女",
"_links": {
"self": {
"href": "http://localhost:8080/api/students/2"
},
"student": {
"href": "http://localhost:8080/api/students/2"
}
}
},
{
"sno": "31",
"sname": "jack",
"ssex": "男",
"_links": {
"self": {
"href": "http://localhost:8080/api/students/3"
},
"student": {
"href": "http://localhost:8080/api/students/3"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/students"
},
"profile": {
"href": "http://localhost:8080/api/profile/students"
},
"search": {
"href": "http://localhost:8080/api/students/search"
}
},
"page": {
"size": 20,
"totalElements": 3,
"totalPages": 1,
"number": 0
}
}