我正在尝试将Entity(TrainingEntity)映射到DTO,其中的一个字段是Set with ManyToMany引用一个AbstractEntity(CoachEntity)的集合,该集合被Single Table分为两个子类:ExternalCoach和InternalCoach。
两个子类都有不同的数据,因此需要两个不同的映射器。
@Entity
@Table(name = "TRAINING")
public class TrainingEntity extends AbstractEntity {
@ManyToMany()
@JoinTable(name = "TRAINING_EMPLOYEE", joinColumns = { @JoinColumn(name = "TRAINING_ID") }, inverseJoinColumns = {
@JoinColumn(name = "COACH_ID") })
private Set<CoachEntity> coachEntities;
@Column(nullable = false)
private TrainingType trainingType;
......some data....
}
抽象教练实体
@Entity
@Table(name = "COACH")
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class CoachEntity extends AbstractEntity {
......some data....
}
教练子类:
@Entity
@DiscriminatorValue("EXTERNAL")
public class ExternalCoachEntity extends CoachEntity {
......some data....
}
@Entity
@DiscriminatorValue("INTERNAL")
public class InternalCoachEntity extends CoachEntity {
......some data....
}
一个用于Abstract Coach类的映射器将无法访问方法和字段的子类,因此对于External和Internal,我需要两个映射器。比我不得不在TrainingMapper类中使用它们,但是(内部示例):
public class CustomTrainingMapper {
public static TrainingDto toTrainingDto(TrainingEntity trainingEntity){
if(trainingEntity == null){
return null;
}
if(trainingEntity.getTrainingType().equals(TrainingType.INTERNAL)){
Set<CoachEntity> coachEntities = trainingEntity.getCoachEntities();
Set<CoachDto> coachDtos = CustomInternalCoachMapper.toDTOSet((Set<InternalCoachEntity>)coachEntities);
}
我得到:
cannot cast from Set<CoachEntity> to Set<InternalCoachEntity>
不进行强制转换,根本看不到带有子类输入的映射器方法。
The method toDTOSet(Set<InternalCoachEntity>) in the type CustomInternalCoachMapper is not applicable for the arguments (Set<CoachEntity>)
在mapper中,我将方法输入更改为抽象Coach类时,看不到子类的方法和字段。
InternalMapper的一部分:
public class CustomInternalCoachMapper {
public static CoachDto toCoachDto(InternalCoachEntity coachEntity) {
if (coachEntity == null) {
return null;
}
EmployeeDto employeeDto = CustomEmployeeMapper.toEmployeeDto(coachEntity.getEmployeeEntity());
return new InternalCoachDto(coachEntity.getId(), coachEntity.getVersion(), coachEntity.getCreateDate(),
coachEntity.getUpdateDate(), coachEntity.getName(), coachEntity.getSurname(), employeeDto);
}
是否可以将此AbstractEntity Set映射到子类DTO中? 我也尝试过使用AbstractDto for Coachs,但是后来我遇到了同样的问题,无法访问子类的getter和setter。