1.创建springboot项目
配pom.xml
添加druid连接池
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
设置mysql版本
<version>5.1.16</version>
配置application
#mysql连接池
spring.datasource.username=root
spring.datasource.password=1024
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#配置jpa
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.database-platform=mysql
spring.jpa.hibernate.ddl-auto=update
3.编写实体类
@Entity(name = "t_book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String author;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
4.写dao接口
public interface BookDao extends JpaRepository<Book,Integer> { }
5.测试rest(增删改查)
item=对应项目路径下+/类名s
就可以实现,在
获取json的数据了
指定id:item/1
分页:item?page=2&size=2
就是2组数据一页,显示第三页的数据
按id倒叙排序:item?sort=id,desc
添加请求: 模拟post提交
修改: PUT请求
删除: DELETE请求
item/要删除的id
6.自定义接口
在接口里写方法名
List<Book> findBookByNameContaining(@Param("name") String name);
//解决方法名过长方法
在类上添加注解
@RestResource(path = "byname",rel = "findbyname")
配置自定义的接口名
@RepositoryRestResource(path = "bs",collectionResourceRel = "bs",itemResourceRel = "b")
7.解决跨域问题
@CrossOrigin
8.自定义rest配置
#配置rest
spring.data.rest.base-path=/api
spring.data.rest.default-page-size=2
也可以通过配置类
创建config
java代码优先级>application配置
@Configuration
public class RestConfig implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setDefaultPageSize(2)
.setBasePath("/api1");
}
}