我有一个@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数据休止符。我相信您可以尝试以下方法:

@Projection(name = "personView",  types = Person.class)
public interface PersonView {
    String getLastname();
}


在您的仓库中,您需要这样的东西:

@RepositoryRestResource(excerptProjection = PersonView.class)
interface PersonRepository extends CrudRepository<Person, Long> {
}

08-03 16:40