轻松搞定RESTFul-spring data rest
2020-10-29 本文已影响0人
前进的码农
首先上官方参考文档
https://docs.spring.io/spring-data/rest/docs/current/reference/html/#reference
https://github.com/spring-projects/spring-hateoas-examples/tree/master/spring-hateoas-and-spring-data-rest
spring的文档还是写的很不错的
第一步引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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>
</dependency>
<!-- http://127.0.0.1:8080/api/browser/index.html 来查看api 记住加上baseurl/-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
设置
设置basepath
spring.data.rest.base-path=/api
这里要注意的是spring-data-rest-hal-browser使用这个api可视化查看文档,如果加了base-path 查看的时候一定要加上这个
数据库设置
spring.datasource.username=**
spring.datasource.password=**
spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ethan?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
编写实体类和数据库层
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userName;
private String passWord;
}
@RepositoryRestResource(path = "user")
public interface UserRepository extends JpaRepository<User,Long> {
@Query(value = "select * from user where user_name=?1",nativeQuery = true)
List<User>findByName(@Param("name") String name);
}
写完这些就大功告成了,记住不要写services和controller层了,现在直接可以增删改查了,增加接口就只需要在dao层直接写方法就行了,是不是很香~~~
最终效果
browser接口查询页面

默认的接口

这里只列举了查询,新增,更新,和删除可以自己尝试!
自定义的查询接口findByName

注意看这里的地址哦!
更多设置请参考官方文档!!