我有一个@Entity Person
类,希望通过Web服务公开它。应该有一个方法只公开所有细节,而端点只公开视图摘录。
我可以将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数据rest。我相信你可以试试这个:
@Projection(name = "personView", types = Person.class)
public interface PersonView {
String getLastname();
}
在你的回购中,你需要这样的东西:
@RepositoryRestResource(excerptProjection = PersonView.class)
interface PersonRepository extends CrudRepository<Person, Long> {
}