Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用SpringMVC和JPA进行JSON序列化_Json_Spring Mvc_Jpa - Fatal编程技术网

使用SpringMVC和JPA进行JSON序列化

使用SpringMVC和JPA进行JSON序列化,json,spring-mvc,jpa,Json,Spring Mvc,Jpa,我有一个使用JavaScript MVC框架Ember.js、Spring MVC控制器层和Spring/JPA业务层的Web应用程序。我的问题是 关于在Spring控制器中将Java输出序列化为JSON 控制器类如下所示: @RequestMapping("countries") @ResponseBody public Collection<Country> getAll() { return countryService.getAllCountries(); } @Req

我有一个使用JavaScript MVC框架Ember.js、Spring MVC控制器层和Spring/JPA业务层的Web应用程序。我的问题是 关于在Spring控制器中将Java输出序列化为JSON

控制器类如下所示:

@RequestMapping("countries")
@ResponseBody
public Collection<Country> getAll() {
  return countryService.getAllCountries();
}

@RequestMapping("country/{id}")
@ResponseBody
public Country getById(@PathVariable Long id) {
  return countryService.getCountry(id);
}
JPA实体包括:

@Entity
class Country {

  @OneToMany
  Collection<State> states;

  //...
}

@Entity
class State {
 // ...
}
方法getAll用于一个屏幕,该屏幕显示每个国家的名称、大小和人口等有限信息集。方法getById用于显示一个国家及其完整数据集的屏幕;这包括其状态子实体的集合

对于JSON序列化,Literature中最建议的解决方案是将Jackson添加到类路径中,并让SpringMVC发挥所有作用。然而,让Jackson盲目地序列化每个属性太粗糙了。但是用Jackson注释(如@JsonProperty或@JsonIgnore)来注释我的JPA字段并不吸引人。首先,它在技术上将我的业务层与接口问题结合起来。其次,它危及维护:JPA属性名称中的任何更改都必须传播到JavaScript代码中,而无需编译器的帮助。第三,也是更重要的一点,实体的属性是否必须序列化在实体级别是不确定的:在getAll情况下,状态必须 不能序列化,但在getById中必须序列化

我能指望Jackson忽略延迟加载的JPA关系吗?例如,在getAll操作中,Jackson会忽略每个国家的states属性吗


还是应该手动实现Java到JSON的序列化?

使用只包含所需字段的DTO,将它们从JPA对象复制到DTO,并向最终用户公开DTO。要在域obejct和DTO之间进行转换,您可以使用,例如,或。谢谢Martin。如果我理解你的帖子,我应该同时使用Jackson和Dozer或其他变压器。因此,@Controller函数将变成:RequestMappingcountries ResponseBody public Collection getAll{Collection countries=countryService.getAllCountries;return transformer.tocountries;}RequestMappingcountries/{id}ResponseBody public CountryDtogetById@PathVariable长id{Country Country=countryService.getCountryid;返回transformer.todcountry;}这就是你的意思吗?像这样的东西应该可以做到。当然,你也可以手动进行映射/转换,但一般来说,使用类似于推土机的东西更容易,尽管你为另一个框架添加了学习曲线。非常感谢你的建议!