现在都流行微服务,各种解耦,于是便要写大量的 controller。但是一些简单的查询可能不需要再写 controller 了。
那就是 spring-data-rest。
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-data-rest</artifactId>
</dependency>
repository
利用这个注解 @RepositoryRestResource,就可以将接口暴露出去。
@RepositoryRestResource(collectionResourceRel = "coffee", path = "/coffee")
public interface CoffeeRepository extends JpaRepository<Coffee, Long> {
List<Coffee> findByNameInOrderById(List<String> list);
@Query(value = "select id,name,price,create_time,update_time from t_coffee c where c.name = ?1", nativeQuery = true)
Coffee findCoffeeByName(@Param(value = "name") String name);
}
访问一下:
http://localhost:8080/coffee/
Response:
{
"_embedded" : {
"coffee" : [ {
"name" : "espresso",
"price" : 2000,
"createTime" : "2019-06-16T21:24:13.068+0800",
"updateTime" : "2019-06-16T21:24:13.068+0800",
"_links" : {
"self" : {
"href" : "http://localhost:8080/coffee/1"
},
"coffee" : {
"href" : "http://localhost:8080/coffee/1"
}
}
}, {
"name" : "latte",
"price" : 2500,
"createTime" : "2019-06-16T21:24:13.070+0800",
"updateTime" : "2019-06-16T21:24:13.070+0800",
"_links" : {
"self" : {
"href" : "http://localhost:8080/coffee/2"
},
"coffee" : {
"href" : "http://localhost:8080/coffee/2"
}
}
}, {
"name" : "capuccino",
"price" : 2500,
"createTime" : "2019-06-16T21:24:13.070+0800",
"updateTime" : "2019-06-16T21:24:13.070+0800",
"_links" : {
"self" : {
"href" : "http://localhost:8080/coffee/3"
},
"coffee" : {
"href" : "http://localhost:8080/coffee/3"
}
}
}, {
"name" : "mocha",
"price" : 3000,
"createTime" : "2019-06-16T21:24:13.071+0800",
"updateTime" : "2019-06-16T21:24:13.071+0800",
"_links" : {
"self" : {
"href" : "http://localhost:8080/coffee/4"
},
"coffee" : {
"href" : "http://localhost:8080/coffee/4"
}
}
}, {
"name" : "macchiato",
"price" : 3000,
"createTime" : "2019-06-16T21:24:13.071+0800",
"updateTime" : "2019-06-16T21:24:13.071+0800",
"_links" : {
"self" : {
"href" : "http://localhost:8080/coffee/5"
},
"coffee" : {
"href" : "http://localhost:8080/coffee/5"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/coffee{?page,size,sort}",
"templated" : true
},
"profile" : {
"href" : "http://localhost:8080/profile/coffee"
},
"search" : {
"href" : "http://localhost:8080/coffee/search"
}
},
"page" : {
"size" : 20,
"totalElements" : 5,
"totalPages" : 1,
"number" : 0
}
}
可以看到,其中返回了各种的查询链接。
那么为什么说他似曾相识呢,是因为我17年第一次接触的项目就是基于 spring 、spring data jpa、spring mvc 的,前端还是用的 angular 1。那时候后端的model类,各种外键,多对一和一对多的关系,service 层调用 repository 层返回的结果就是上图所示。后来的项目都是基于 mybatis,很少遇到这些了。