如何将JPA OneToMany关系转换为DTO [英] How to convert a JPA OneToMany relationship to DTO
问题描述
我有一个课程计划
,其中有一个活动
的列表。 活动
类具有对单个计划
的引用。因此,存在这样的 OneToMany 关系:
I have a class Plan
in which there is a list of Activity
. The Activity
class has a reference to a single Plan
. Hence there is a OneToMany relationship like this:
@Entity
public class Plan {
@OneToMany(mappedBy = "Plan")
private List<Activity> activities;
}
@Entity
public class Activity {
@ManyToOne
@JoinColumn(name= "PLAN_ID")
private Plan plan;
}
我需要将它们转换为DTO以发送到表示层。因此,我有一个汇编程序类,可以简单地将域对象转换为POJO。
I need to convert them to DTOs to be sent to presentation layer. So I have an assembler class to simply convert domain objects to POJO.
public class PlanAssembler {
public static PlanDTO makeDTO(Plan p) {
PlanDTO result = new PlanDTO();
result.setProperty(p.getProperty);
...
for (Activity a: p.getActivity()) {
// Here I need to iterate over each activity to convert it to DTO
// But in ActivityAssembler, I also need PlanDTO
}
您可以看到,在 PlanAssembler
中,我需要遍历所有活动并将其转换为 ActivityDTO
,但是麻烦的是,在 ActivityAssembler
中,我还需要 PlanDTO
来构造 ActivityDTO
。这将是无限循环。我该如何解决呢?
As you can see, in PlanAssembler
, I need to iterate over all activities and convert them to ActivityDTO
but the trouble is, in ActivityAssembler
I also need the PlanDTO
to construct the ActivityDTO
. It's gonna be an infinite loop. How can I sort this out?
请帮忙。
推荐答案
这不会是无限循环,因为您必须使用在循环之前创建的PlanDTO对象结果。参见下面的代码。
It won't be an infinite loop because you have to use the PlanDTO object result which you have just created before the loop. See the code below.
注意:我还是建议您使用一个可以为您完成此工作的框架。
Note : Still I suggest to go for a framework which will do this stuff for you.
public class PlanAssembler {
public static PlanDTO makeDTO(Plan p) {
PlanDTO result = new PlanDTO();
result.setProperty(p.getProperty);
...
for (Activity a: p.getActivity()) {
ActivityDTO activityDTO = new ActivityDTO();
// Here I need to iterate over each activity to convert it to DTO
// But in ActivityAssembler, I also need PlanDTO
//Code to convert Activity to ActivityDTO.
activityDTO.setPlan(result);
}
这篇关于如何将JPA OneToMany关系转换为DTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!