【发布时间】:2018-07-03 05:55:43
【问题描述】:
我的项目中有 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;
}
有人可以帮忙吗...
编辑:用 get 替换 load 解决了这个问题。但现在 /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;
}
【问题讨论】:
-
不要使用
load。使用get。也不要使用new Integer,直接使用id(创建new Integer会增加开销)。 -
@M.Deinum 它与 get() 一起使用.. 你能告诉我为什么它没有与 load() 一起使用吗?
-
load创建实际对象的代理而不实际访问数据库,get将实际从数据库中检索对象。如果正在进行的事务仍然处于活动状态,load将起作用,但是由于您不在服务方法之外,因此情况并非如此,并且代理无法从数据库中获取实际数据。 -
@M.Deinum 是的,即使我对使用 load() 有疑问。我现在对 /getAllCountries 有不同的错误。你能帮我吗?我已经更新了问题
-
这是一个完全不同的问题,不要在一个问题中问 2 个问题。
标签: java xml spring hibernate rest