Reputation: 86915
I have an @Entity Person
class, and want to expose that via a webservice. There should be a method just exposing all details, and and endpoint only exposing a view excerpt.
Can I use Spring @Projection
for that purpose without having to manually extract the fields I want to expose? I'd prefer just returning a List<Person>
but render only certain details for certain endpoints.
@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> {
}
Upvotes: 0
Views: 139
Reputation: 4187
Note that @Projection
only works with spring data rest. I believe you could try this:
@Projection(name = "personView", types = Person.class)
public interface PersonView {
String getLastname();
}
And on your repo, you need something like this:
@RepositoryRestResource(excerptProjection = PersonView.class)
interface PersonRepository extends CrudRepository<Person, Long> {
}
Upvotes: 1