【发布时间】:2016-01-08 21:04:56
【问题描述】:
我正在寻找一种动态方式来控制使用查询参数从请求返回的响应对象。
我使用 Jersey 2.x 和 Hibernate 4 来管理实体以及一些用于安全性的 Spring 洒水等。问题是 Jersey 没有序列化附加的实体,而只是序列化基本实体。我目前正在使用com.fasterxml.jackson.datatype.hibernate4。这给了我一些灵活性来处理如何使用 JPA fetch=Eager 等加载子实体和父实体。但是我真的想让这个动态。
我通过指定?with=<someentity> 来指定要附加的实体尝试了一个简单的动态加载。获取实体时,我使用反射调用某个实体的 getter,它成功地附加了实体,但是当将实体发送出去时,它没有序列化附加的实体。
这是我正在尝试做的一个超级简单的例子。这实际上只是一个分开的部分,但想法就在那里。问题是当我从服务器获取 Campaign 对象时,它没有序列化通过调用 loadEntity 附加的实体。
@Path("campaign")
public class CampaignResource {
@GET
@Path("{entity_id}")
public Campaign find(@PathParam("entity_id") final Long id, @QueryParam("with") final String with) {
T entity = repository.findOne(id);
load(entity, with);
return entity;
}
/**
* This is used to attach entities that are requested via the api.
*
* @param entity
* @param with
*/
@SuppressWarnings("unused")
protected void loadWithEntities(T entity, final String with) {
String[] withFields;
if (with.contains(",")) {
// Split the with clause into separate values
withFields = with.split(",");
} else {
// Single with clause
withFields = new String[] { with };
}
for (String field : withFields) {
final String getterMethodName = getMethodGetterForField(field);
Method method = null;
try {
method = entityClass.getMethod(getterMethodName);
if (method != null) {
logger.info("Loading entity " + getterMethodName);
// Some odd reason we have to assign the variable so that it
// is attached.
final Object attached = method.invoke(entity);
}
} catch (Exception e) {
logger.error("Unable to find method name %s ", getterMethodName, e);
}
}
}
}
【问题讨论】:
标签: java jersey jackson jersey-2.0