0
我有兩個實體,foo和bar。一個富可以有0-n條。Spring RestFul jquery jpa-criteria - HEAD返回1而不是0
在foo和酒吧,我有這樣的數據:
---- foo-table (2 rows) --- ---- bar-table (1 row) ----
fooID barID fk_foo
1 1 1
2
Foo和酒吧都在寧靜的服務,我想找到一條id 2
foo的酒吧的數量。
因爲fooID#2沒有引用欄,所以計數應該是0.這裏我的問題:服務報告我參考foo#2的條的計數是1
而不是0
!
我的控制器:
@Autowired(required = false)
private final BarFilter[] filters = new BarFilter[0];
/**
* Count all bars available.
*/
@RequestMapping(value="/bar", method = RequestMethod.HEAD)
public void countBar(final HttpServletResponse response, final HttpServletRequest request) {
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
final Root<Bar> root = criteriaQuery.from(Bar.class);
criteriaQuery.select(criteriaBuilder.count(root));
for (final BarFilter filter: filters) {
filter.count(request, criteriaQuery, root, criteriaBuilder);
}
final Query query = entityManager.createQuery(criteriaQuery);
final Number count = (Number)query.getSingleResult();
LOG.info("Found " + count + "x Bar.");
response.setIntHeader("count", count.intValue());
}
這是BarFilter執行的計數方法:
@Override
public void count(HttpServletRequest request, CriteriaQuery<Long> query, Root<Bar> root, CriteriaBuilder builder) {
final Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
final String name = parameterNames.nextElement();
String prop = name;
if (!prop.contains("[]")) {
prop = prop.replace("]", "");
prop = prop.replace("[", ".");
final String[] split = prop.split("\\.");
Path<Object> path = null;
try {
final Root<Bar> r = query.from(Bar.class);
for (final String property : split) {
if (path == null) {
path = r.get(property);
} else {
path = path.get(property);
}
}
query.where(builder.equal(path, request.getParameter(name)));
} catch (final IllegalArgumentException e) {
System.out.println(prop + " not found");
}
}
}
}
這是jQuery的請求:
jQuery.ajax({
url: 'rest/bar',
type: 'HEAD',
dataType: 'json',
data: {foo:{id:2}},
success: function(data, state, xhr){
alert(xhr.getResponseHeader('count'));
},
error: function(err) {
alert('error:' + err.status);
}
});
鉻給我此請求在網絡選項卡中: http://localhost:8080/MyServer/rest/bar?foo%5Bid%5D=2
擁有此查詢字符串:
而這種響應報頭:
問:爲什麼我成爲1而不是0計數?