SPEL:要映射列表元素的投影



i hava a spring data mongodb托管实体,该实体在其子集合中存储元素列表。为了通过Spring MVC仅返回该实体的子集,我正在使用投影来自定义数据对象的视图。

简化的样本可视化我的设置:

@Getter
@Setter
@Document(collection = "test")
public class CompanyEntity {
    @Id
    private String id;
    private List<Employee> employees;
    ...
}

用户是:

@Getter
@Setter
public class Employee {
    private String id;
    private String name;
    ...
}

视图是一个看起来像这样的简单接口:

public interface CompanyView {
    String getId();
    @Value("#{target.employees.![name]}")
    List<String> getEmployeeNames();
}

虽然我能够直接通过#{target.employees.![name]}直接将员工的名称投射到列表中,但我以某种方式尝试使用employee.id用作键,将当前代码替换为键,而employee.name作为值。

这是可能的还是我必须编写自定义功能?

好吧,我想我找到了我满意的解决方案。

为了创建类似:

的东西
@Value("#{target...}")
Map<String, String> getEmployees();

我现在正在定义一个名为 EmployeeView的新子投影,我用作List返回的类型。

public interface EmployeeView {
    String getId();
    String getName();
}

CompanyView中的定义确实看起来像这样:

@Value("#{target.employees}")
List<EmployeeView> getEmployees();

这仅返回返回数据中员工的有限子集。

最新更新