【发布时间】:2021-10-28 12:09:50
【问题描述】:
我最近了解了 dto,所以在我的应用程序中,我尝试使用 JPQL 查询获取 DTO,但我得到了异常。
这是我的代码:
public class Teacher {
@ElementCollection
@CollectionTable(name = "teacher_phone_number",
joinColumns = {@JoinColumn(name = "teacher_id")})
@Column(name = "phone_number")
private Set<String> phoneNumbers;
// getter setters
}
public class TeacherDTO {
private long id;
private String teacherName;
private Set<String> phoneNumber;
public TeacherDTO(long id, String teacherName, Set<String> phoneNumber) {
this.id = id;
this.teacherName = teacherName;
this.phoneNumber = phoneNumber;
}
//Setter getters
}
public class TeacherRepositoryImpl {
@Override
public TeacherDTO fetchTeacherDTOById(Long id) {
return entityManager.createQuery("select new service.dto.TeacherDTO(t.id,
concat(t.firstName, ' ', t.lastName)" + ", tp.phoneNumbers)
from Teacher t join t.phoneNumbers tp where
t.id = :id", TeacherDTO.class).setParameter("id", id).getSingleResult();
}
}
伙计们,我想将 DTO 添加到我的服务层,所以我不得不使用 JPQL 来获取 dto 实体。但我得到这个错误:
Exception in thread "main" java.lang.IllegalArgumentException:
org.hibernate.QueryException: cannot dereference scalar collection
element: phoneNumbers [select new service.dto.TeacherDTO(t.id,
concat(t.firstName, ' ', t.lastName), tp.phoneNumbers) from
model.Teacher t join t.phoneNumbers tp where t.id = :id]
提前致谢!
【问题讨论】: