2016-11-28 80 views
1

我有一个Spring Data MongoDB托管实体,它存储子集合中的元素列表。为了仅通过Spring MVC返回此实体的一个子集,我使用projections来定制数据对象上的视图。SpEL:映射列表元素的投影

简化样品形象化我的设置:

@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作为值来替换当前代码。

这是甚至可能或我必须写一个custom function因此呢?

回答

0

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

为了创造这样的:

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

现在我定义一个新的副突起称为EmployeeView我类型的List返回使用。

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

CompanyView定义看起来现在这个样子:

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

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