背景说明
Spring Data REST 作为 Spring Data 项目的子集,开发者只需使用注解 @RepositoryRestResource
标记,就可以把整个 Repository 转换为 HAL 风格的 REST 资源,目前已支持 Spring Data JPA、Spring Data MongoDB、Spring Data Neo4j等等。
上手示例
下面的示例,可以帮助大家快速了解下使用 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的用户 |
以上这些动作都有相应的触发事件,我们可以参考文档说明并根据实际需求做补充监听。
参考文档
Spring Data REST Reference Guide
文章已授权转载,原文链接:让 Restful API 更加 Simpler:Spring Data Rest