繁体   English   中英

XML错误响应Spring REST和休眠状态

[英]XML incorrect response Spring REST and hibernate

我有Spring REST,并且在我的项目中处于休眠状态。 我想以xml格式显示响应,但是无论我在URL中传递的id如何,我都会得到如下所示的不正确的xml响应:

<COUNTRY id="0">
<population>0</population>
</COUNTRY>

我点击的网址是:

http://localhost:8080/SpringRestHibernateExample/getCountry/2

通过调试,我发现ID正确传递到DAO层,并且正确的国家/地区也已获取。 渲染不正确。 这是我的课

控制者

@RequestMapping(value = "/getCountry/{id}", method = RequestMethod.GET, 
headers = "Accept=application/xml",
        produces="application/xml")
public Country getCountryById(@PathVariable int id) {

    return countryService.getCountry(id);
}

模型

@XmlRootElement (name = "COUNTRY")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
@Table(name="COUNTRY")
public class Country{

@XmlAttribute
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;

@XmlElement
@Column(name="countryName")
String countryName; 

@XmlElement
@Column(name="population")
long population;

public Country() {
    super();
}

服务

@Transactional
 public Country getCountry(int id) {
    System.out.println("service"+id);
    return countryDao.getCountry(id);
}

public Country getCountry(int id) {
    System.out.println("dao"+id);
    Session session = this.sessionFactory.getCurrentSession();
    Country country = (Country) session.load(Country.class, new Integer(id));

    return country;
}

有人可以帮忙吗...

编辑:用获取替换负载解决了该问题。 但是现在对于/ getAllCountries我收到以下错误:

The resource identified by this request is only capable of generating 
responses with characteristics not acceptable according to the request 
"accept" headers.

下面是控制器

 @RequestMapping(value = "/getAllCountries", method = 
 RequestMethod.GET,produces="application/xml",
        headers = "Accept=application/xml")
 public List<Country> getCountries() throws CustomerNotFoundException{

 List<Country> listOfCountries = countryService.getAllCountries();
 return listOfCountries;
}

问题是您的DAO方法使用Session.load而不是Session.get

loadget之间的区别是load (通常总是)返回一个惰性代理。 它仅在实际请求数据时才获取实际的基础数据(由于数据库中的延迟检查,这也可能导致EntityNotFoundException异常延迟)。 现在,通常您不会注意到任何懒惰的东西(也许在性能上),但是在这种情况下,您会注意到。 您处于活动事务之外(因此处于Session ),并且由于该代理不再能够从数据库中获取所需的数据(并且由于没有任何东西,您将获得0因为这是int的默认值)。

我建议将参数名称添加到@PathVariable

示例@PathVariable(“ id”)

同样,如果您使用对象作为ID,则可以像整数一样在所有层中使用它,而不是int。

另外,如果不需要,则Integer可以为null,将Pathdariable设置为required = true。 如果不允许为null

最后,如果您不打算使用该对象并直接将其返回,请使用session.get而不是session.load

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM