我试图找出如何将请求中的数据映射到Hibernate对象,问题是输入的数据可能位于对象或子对象上,而字段数据并不一定为已知--表单被配置为包含和收集所需的数据。
粗略地说,物体是这样的:
Job {
String title;
@ManyToOne
@JoinColumn(name = "location_id")
JobLocation location;
}
JobLocation {
int id;
String description;
double latitude;
double longitude;
}因此,如果用户定义了他们想要编辑JobLocation描述,我们将返回到请求中,类似于
{ jobLocationDescription: 'Santa Fe' }如何将其映射回我正在处理的Job的子级?在节省时间时,我所拥有的只是对Job的引用,所有其他项都可能会根据它们在下拉列表中选择的内容而变化,其中一个选项是存储引用(如job.location.description ),并使用getter和使用反射来执行进程驱动选项:
String[] field = requestField.split(".");
Entity ent = (get object from field[0]);
if (field.length > 2) {
ent = ent.get[get method name from next field position]();
}
ent.set[get method name from last field[] value](requestValue);可悲的是,没有什么可以说它不可能是多个级别,为了得到我们目前认为我们必须使用反射的方法。还有其他更好的方法来完成这种操作吗?还是我们只需要费力地完成这些操作呢?
发布于 2015-08-05 10:59:59
在我们的项目中,我有几乎类似的要求。最后,我们使用反射+注释进行映射。简单地说,我们有这样的东西来构造对象。
class Job {
String title;
@ManyToOne
@JoinColumn(name = "location_id")
@EntityMapper(isRef="true")//Custom Annotation
JobLocation location;
}
class JobLocation {
@EntityMapper(fieldName="jobLocationId")
int id;
@EntityMapper(fieldName="jobLocationDescription")//Custom Annotation
String description;
double latitude;
double longitude;
}如果您还没有理解我的意思,那么我们创建了自定义注释,并编写了一个实用工具方法,通过反射循环遍历包含注释的元素,如下所示:
for (Field field : object.getClass().getDeclaredFields()) {
//check for the EntityMapper annotation
if (field.getAnnotation(EntityMapper.class) != null) {
.
.
.//Use more reflection to use getters and setters to create and assign values from the JSON request.
}
}发布于 2015-07-27 22:02:41
如果在编译时知道要调用的方法的名称,则不必使用反射。听起来你需要倒影。但是,这并不意味着您必须使用原始的java.lang.reflect API,直接使用这个API非常痛苦。如果您已经在使用Spring,那么BeanWrapperImpl是一个非常好的实用工具,它可以使用现有的ConversionService将输入转换为目标类型。否则,我会建议公域BeanUtils,它在没有弹性的情况下做同样的事情。这两个库都知道如何处理嵌套属性和Map-valued属性。
https://stackoverflow.com/questions/31658701
复制相似问题