Spring引导控制器端点和ModelAttribute深度访问
我想知道如何在GET请求中访问深层集合类属性。我的端点通过@ModelAttribute注释映射我的查询字符串: 鉴于:Spring引导控制器端点和ModelAttribute深度访问,spring,spring-boot,binding,controller,modelattribute,Spring,Spring Boot,Binding,Controller,Modelattribute,我想知道如何在GET请求中访问深层集合类属性。我的端点通过@ModelAttribute注释映射我的查询字符串: 鉴于: public class MyEntity { Set<Item> items; Integer status; // getters setters } public class Item { String name; // getters setters } 公共类MyEntity { 设置项目; 整数状态; //吸
public class MyEntity
{
Set<Item> items;
Integer status;
// getters setters
}
public class Item
{
String name;
// getters setters
}
公共类MyEntity
{
设置项目;
整数状态;
//吸气剂二传手
}
公共类项目
{
字符串名;
//吸气剂二传手
}
和我的GET请求:localhost/entities/?status=0&items[0]。name=Garry
产生吼叫行为
@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."
}
@RequestMapping(path=“/entities”,method=RequestMethod.GET)
公共列表由(@modeldattribute MyEntity实体)查找{
//entity.getItems()为空,并引发错误:“索引属性路径“items[0]”中引用的属性既不是数组,也不是列表,也不是映射。”
}
我的“项目”应该是数组、列表还是映射?如果是这样的话,还有其他方法可以继续使用as Set?看起来
Set有问题
如果要为项目集合使用Set,则必须对其进行初始化并添加一些项目:
e、 g.像这样:
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
}
这两个URL都映射,无需初始化任何内容,也可映射不同数量的项目
注意,我没有使用@modeldattribute
,只是将类设置为parameter
@GetMapping("map")//GetMapping is just a shortcut for RequestMapping
public MyEntity map(MyEntity myEntity) {
return myEntity;
}
主题外
在Get请求中映射复杂对象对我来说就像是一种代码味道。
通常,Get方法用于获取/读取数据,url参数用于指定应用于筛选必须读取的数据的值
如果要插入或更新某些数据,请使用POST、PATCH或PUT,并将要插入/更新的复杂对象作为JSON放入请求正文中(您可以在Spring控制器中使用@RequestBody
)进行映射。看起来集合有问题
如果要为项目集合使用Set,则必须对其进行初始化并添加一些项目:
e、 g.像这样:
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
}
这两个URL都映射,无需初始化任何内容,也可映射不同数量的项目
注意,我没有使用@modeldattribute
,只是将类设置为parameter
@GetMapping("map")//GetMapping is just a shortcut for RequestMapping
public MyEntity map(MyEntity myEntity) {
return myEntity;
}
主题外
在Get请求中映射复杂对象对我来说就像是一种代码味道。
通常,Get方法用于获取/读取数据,url参数用于指定应用于筛选必须读取的数据的值
如果要插入或更新某些数据,请使用POST、PATCH或PUT并将要插入/更新的复杂对象作为JSON放入请求正文中(您可以使用@RequestBody
在Spring控制器中映射该对象)。您的实体是否使用hibernate映射?请提供更多详细信息,返回语句在哪里?您的实体是否使用hibernate映射?请提供更多详细信息,您的退货声明在哪里?谢谢@Evgeni。对不起,回信太晚了。我改变了我的方法,但我会尝试你的第一个网址。是的,这似乎是一种代码味道,但我正在使用Spring数据示例功能,它将我的查询映射到一个助手实体,然后在我的sql查询的WHERE子句中转换每个非空属性。对于我的管理页面功能,这是非常有用的。谢谢@Evgeni。对不起,回信太晚了。我改变了我的方法,但我会尝试你的第一个网址。是的,这似乎是一种代码味道,但我正在使用Spring数据示例功能,它将我的查询映射到一个助手实体,然后在我的sql查询的WHERE子句中转换每个非空属性。对于我的管理页面功能,这是非常有用的。