我试图弄清楚如何将请求中的数据映射到Hibernate对象,问题是进入的数据可能在对象或子对象上,并且字段数据不一定是已知的 - 用户配置表单以包含和收集所需数据.
粗略地说,对象是这样的:
Job {
String title;
@ManyToOne
@JoinColumn(name = "location_id")
JobLocation location;
}
JobLocation {
int id;
String description;
double latitude;
double longitude;
}
Run Code Online (Sandbox Code Playgroud)
因此,如果用户已经定义了他们想要编辑JobLocation描述,我们将在请求中返回一些内容
{ jobLocationDescription: 'Santa Fe' }
Run Code Online (Sandbox Code Playgroud)
这是如何映射回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);
Run Code Online (Sandbox Code Playgroud)
可悲的是,没有什么可以说它不能是多层次的,并且为了获得我们目前认为必须使用反射的方法.还有其他更好的方法来做这种类型的操作还是我们只是不得不勉强通过这个?
我的项目中几乎有类似的要求.我们最终使用了反射+注释进行映射.简而言之,我们有这样的东西来构造对象.
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;
}
Run Code Online (Sandbox Code Playgroud)
如果您没有得到我的意思,我们创建了自定义注释,我们编写了一个实用程序方法,通过反射循环遍历具有注释的元素,如下所示:
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.
}
}
Run Code Online (Sandbox Code Playgroud)