我正在寻找一种动态方法来控制使用查询参数从请求返回的响应对象。
我使用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);
}
}
}
}
Jersey有实体数据筛选来处理这个用例。希望你使用的是Jersey的后期版本,因为Jackson直到(2.14:-)到2.16之间才得到支持。懒得在什么时候检查。我猜你在用jersey-media-json-jackson
。如果您的版本引入了jersey-entity-filtering
依赖项,您就会知道它是否受支持。您不需要添加任何其他内容。
您只需要配置三件事:
- 注册
SelectableEntityFilteringFeature
-
配置查询参数名称。
.property(SelectableEntityFilteringFeature.QUERY_PARAM_NAME, "with")
有不同类型的过滤功能,但这里是关于查询参数过滤的部分。没有太多信息,因为好吧,没有太多的信息可以告诉。您真正需要知道的是如何配置,并且它可以按照您的期望工作,即?with=prop1,prop2,prop3