我有一个@Entity Person
类,并希望通过网络服务公开它。应该有一个方法只公开所有详细信息,并且端点仅公开 View 摘录。
我可以使用 Spring @Projection
为此目的,无需手动提取我想要公开的字段?我宁愿只返回 List<Person>
但仅呈现某些端点的某些详细信息。
@RestController
public class BookingInfoServlet {
@Autowired
private PersonRepository dao;
@GetMapping("/persons")
public List<Person> persons() {
return dao.findAll();
}
//TODO how can I assign the Projection here?
@GetMapping("/personsView")
public List<Person> persons() {
return dao.findAll();
}
//only expose certain properties
@Projection(types = Person.class)
public interface PersonView {
String getLastname();
}
}
@Entity
public class Person {
@id
long id;
String firstname, lastname, age, etc;
}
interface PersonRepository extends CrudRepository<Person, Long> {
}
最佳答案
请注意,@Projection
仅适用于 Spring Data Rest。我相信你可以尝试这个:
@Projection(name = "personView", types = Person.class)
public interface PersonView {
String getLastname();
}
在你的仓库中,你需要这样的东西:
@RepositoryRestResource(excerptProjection = PersonView.class)
interface PersonRepository extends CrudRepository<Person, Long> {
}
关于java - 如何将 @Projection 分配给 @GetMapping spring servlet 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51404922/