背景说明

Spring Data REST 作为 Spring Data 项目的子集,开发者只需使用注解 @RepositoryRestResource 标记,就可以把整个 Repository 转换为 HAL 风格的 REST 资源,目前已支持 Spring Data JPA、Spring Data MongoDB、Spring Data Neo4j等等。

Spring Data REST Introduction

上手示例

下面的示例,可以帮助大家快速了解下使用 Spring Data REST 所带来的便利,当然了,大部分业务场景都不会有这么的简单,因此在实际项目中并不推荐使用:

添加依赖

<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

核心代码

  • 配置 application.yml
spring:
data:
rest:
# Restful API 路径前缀
base-path: api
max-page-size: 10
default-page-size: 5
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&zeroDateTimeBehavior=convertToNull&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&tinyInt1isBit=false
username: root
password: root
mvc:
servlet:
load-on-startup: 1
throw-exception-if-no-handler-found: true
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
hibernate:
ddl-auto: update
show-sql: true
open-in-view: false
jackson:
time-zone: GMT+8
logging:
level:
web: debug
  • 定义实体和性别枚举类
@Data
@MappedSuperclass
@NoArgsConstructor
@AllArgsConstructor
public class BaseEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@UpdateTimestamp
@Column(nullable = false)
private Date updateTime;

@CreationTimestamp
@Column(nullable = false, updatable = false)
private Date createTime;

@Version
private Long version;

@NotNull
private Boolean deleted = false;

}
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class User extends BaseEntity {

@NotBlank
private String name;

@NotNull
@Enumerated
private Gender gender;

}
public enum Gender {

/**
* 男
*/
MAN,

/**
* 女
*/
WOMAN,

/**
* 未知
*/
UNKNOWN;

}
  • 添加 Repository
@RepositoryRestResource(path = "user")
public interface UserRepository extends JpaRepository<User, Integer> {

/**
* /api/user/search/findByName
*/
List<User> findByName(@Param("name") String name);

/**
* /api/user/1
*/
@Override
@Modifying
@Query("UPDATE User u SET u.deleted = true WHERE u.id = ?1")
void deleteById(Integer id);

}
  • 初始化测试数据
@SpringBootApplication
public class SpringBootDataRestApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootDataRestApplication.class, args);
}

@Resource
private UserRepository userRepository;

/**
* 初始化数据
*/
@PostConstruct
public void init() {
EnumSet<Gender> genders = EnumSet.allOf(Gender.class);
List<User> users = new LinkedList<>();
for (int i = 0; i < 10; i++) {
User user = User.builder().name("test" + i)
.gender(genders.stream().findAny().get()).build();
users.add(user);
}
userRepository.saveAll(users);
}

}

测试说明

启动 Application,此时已暴露出来的 Restful API 接口包含几个:

请求方式 请求路径 接口说明
GET http://ip:port/api/user{?page,size,sort} 分页查询
GET http://ip:port/api/user/1 查询id为1的用户
GET http://ip:port/api/user/search/findByName?name=xxx 查询name为xxx的用户
POST http://ip:port/api/user 新增用户
PUT http://ip:port/api/user/1 更新id为1的用户
DELETE http://ip:port/api/user/1 删除id为1的用户

Test

以上这些动作都有相应的触发事件,我们可以参考文档说明并根据实际需求做补充监听。

参考文档

Spring Data REST Reference Guide

示例源码
欢迎关注我的个人公众号:超级码里奥
如果这对您有帮助,欢迎点赞和分享,转载请注明出处

最后更新: 2019年04月09日 10:30

原始链接: https://blog.mariojd.cn/spring-data-rest-simple-reference-example.html

× 支持创作
打赏二维码