java使用带有@RequestParam的springboot内部@Controller来提供搜索方法
我正在用spring boot构建一个后端RESTAPI
实体:
@Entity
public class Club {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull
@Column(unique=true)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
存储库:
@RepositoryRestResource
public interface ClubRepository extends JpaRepository<Club, Long>, JpaSpecificationExecutor<Club> {
}
这本身就在http://host/clubs
处公开了一个rest端点,太好了。现在,我想允许url中的一些参数用于搜索目的,所以我开始遵循http://www.baeldung.com/rest-api-search-language-spring-data-specifications的说明
但它们最终创建了一个自定义@Controller
来传递请求参数:
@Controller
public class ClubController {
@Autowired
private ClubRepository repo;
@RequestMapping(method = RequestMethod.GET, value = "/clubs")
@ResponseBody
public List<Club> search(@RequestParam(value = "search") String search) {
/* ... */
return repo.findAll(spec);
}
}
因此,您可以看到,它们最终调用存储库的findAll方法,只是传递一个基于查询参数构建的规范。很简单,但我真的希望不必为我的每个域对象创建额外的控制器。换句话说,有没有办法通过直接注释(例如)存储库中的@Entity
或重写方法(如findAll
方法)来提供此搜索功能
# 1 楼答案
更好的方法是使用QueryDsl,而不是criteria API。Spring Data和Spring Data Rest将“免费”为您提供许多优秀的功能,而不是一些基本配置
https://spring.io/blog/2015/09/04/what-s-new-in-spring-data-release-gosling#spring-data-rest
https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
一个配置好的存储库界面就是:
然后可以使用参数的动态组合查询端点:
例如
http://host/clubs?name=someName
http://host/clubs?name=someName&otherProperty=X&sort=name,desc
无需进一步的代码,即无需定制控制器、规范和查询方法
要配置Maven,只需在包含实体的模块中的POM中添加以下内容:这将生成必要的“查询”类