2016-11-28 84 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(); 

這僅返回返回的數據中員工的有限的子集。