2017-07-29 22 views
1

我想知道如何在GET请求中访问深层集合类属性。我的端点映射通过@ModelAttribute注解我的查询字符串:Spring引导控制器enpoint和ModelAttribute深入访问

鉴于:

public class MyEntity 
{ 
    Set<Item> items; 
    Integer status; 
    // getters setters 
} 

public class Item 
{ 
    String name; 
    // getters setters 
} 

我的GET请求:本地主机/实体/状态= 0 &项目[0]。名称=加里

产生波纹管行为?

@RequestMapping(path = "/entities", method = RequestMethod.GET) 
public List<MyEntity> findBy(@ModelAttribute MyEntity entity) { 
    // entity.getItems() is empty and an error is thrown: "Property referenced in indexed property path 'items[0]' is neither an array nor a List nor a Map." 
} 

我的“项目”应该是一个数组,列表或映射?如果是这样,那么有其他选择继续使用设置??

感谢

+0

是用hibernate映射的实体吗?请包括更多细节您的退货声明在哪里? – ketrox

回答

0

看起来有一些问题与Set<Item>

如果你想使用设置了items收集你必须初始化它,添加一些项目:

例如像这样:

public class MyEntity { 
    private Integer status; 
    private Set<Item> items; 

    public MyEntity() { 
     this.status = 0; 
     this.items = new HashSet<>(); 
     this.items.add(new Item()); 
     this.items.add(new Item()); 
    } 
//getters setters 
} 

但随后你就可以设置此2项仅值:

这将工作:http://localhost:8081/map?status=1&items[0].name=asd&items[1].name=aaa

这是行不通的:http://localhost:8081/map?status=1&items[0].name=asd&items[1].name=aaa&items[2].name=aaa

它会说:Invalid property 'items[2]' of bean class MyEntity.

但是,如果切换到列表:

public class MyEntity { 
    private Integer status; 
    private List<Item> items; 
} 

这两个urls地图无需初始化任何东西和不同数量的项目。

,我没有使用 @ModelAttribute

笔记,只需设置类作为放慢参数

@GetMapping("map")//GetMapping is just a shortcut for RequestMapping 
public MyEntity map(MyEntity myEntity) { 
    return myEntity; 
} 

Offtopic

映射一个复杂的对象在用GET请求听起来像一个代码味道给我。 通常,Get方法用于获取/读取数据,url参数用于指定应用于过滤必须读取的数据的值。

如果要插入或更新某些数据,请使用POST,PATCH或PUT,然后将要插入/更新的复杂对象作为JSON放入请求主体(可以使用@RequestBody将其映射到Spring Controller中)。

+0

谢谢@Evgeni。不好意思回复你太晚了。我改变了我的方法,但我会尝试你的第一个网址。 是的,它似乎是一种代码气味,但我使用Spring数据示例功能,它将我的查询映射到一个帮助实体,然后转换我的SQL查询的WHERE子句中的每个非空属性。对于我的管理页面功能它非常有帮助。 – user3810036