【发布时间】:2018-06-06 11:57:14
【问题描述】:
我有以下实体:
@Entity
public class CityExpert {
@Id
private long id;
@OneToOne
private User user;
@OneToMany(mappedBy = "cityExpert")
private List<CityExpertDocument> documents;
// Lots of other fields...
}
@Entity
public class CityExpertDocument {
@Id
private long id;
@ManyToOne
private CityExpert cityExpert;
// Lots of other fields...
}
@Entity
public class User {
@Id
private long id;
private String name;
private String email;
// Lots of other fields...
}
我有以下 HQL 查询,其中我选择了 CityExperts 的子集:
"select " +
"e " +
"from " +
"CityExpert e " +
"where " +
"( (lower(e.user.name) like concat('%', lower(?1), '%') or e.user.name is null) or ?1 = '' ) " +
"and " +
"( (lower(e.user.phone) like concat('%', lower(?2), '%') or e.user.phone is null) or ?2 = '' ) "
但是,由于CityExpert 中的字段太多,我不想选择所有字段。因此,我将查询更改如下:
"select " +
"e.user.name, " +
"e.user.email, " +
"e.documents " +
"from " +
"CityExpert e " +
"where " +
"( (lower(e.user.name) like concat('%', lower(?1), '%') or e.user.name is null) or ?1 = '' ) " +
"and " +
"( (lower(e.user.phone) like concat('%', lower(?2), '%') or e.user.phone is null) or ?2 = '' ) "
但是,显然我们不能在这样的实体中选择一对多字段,因为我在前面的查询中得到了一个MySQLSyntaxErrorException(请参阅this question)。因此,我将查询更改为以下内容:
"select " +
"e.user.name, " +
"e.user.email, " +
"d " +
"from " +
"CityExpert e " +
"left join " +
"e.documents d" +
"where " +
"( (lower(e.user.name) like concat('%', lower(?1), '%') or e.user.name is null) or ?1 = '' ) " +
"and " +
"( (lower(e.user.phone) like concat('%', lower(?2), '%') or e.user.phone is null) or ?2 = '' ) "
但是,这次结果变成了List<Object[]>,而不是List<CityExpert>。
我创建了以下 DTO:
public class CityExpertDTO {
private String name;
private String email;
private List<CityExpertDocument> documents;
}
但是,我不知道应该如何将 Hibernate 返回的结果映射到List<CityExpertDTO>。我的意思是,我可以手动执行此操作,但肯定有 Hibernate 提供的自动化解决方案。
我正在使用 Spring Data JPA 并使用 HQL,如下所示:
public interface CityExpertRepository extends JpaRepository<CityExpert, Long> {
@Query(
"select " +
"e " +
"from " +
"CityExpert e " +
"where " +
"( (lower(e.user.name) like concat('%', lower(?1), '%') or e.user.name is null) or ?1 = '' ) " +
"and " +
"( (lower(e.user.phone) like concat('%', lower(?2), '%') or e.user.phone is null) or ?2 = '' ) "
)
Set<CityExpert> findUsingNameAndPhoneNumber(String name,
String phoneNumber);
}
如何将结果映射到CityExpertDTO?
【问题讨论】:
-
我认为你不能直接将条目映射到 dto 我有同样的问题,我只是创建本机查询并选择所有数据并通过 for 循环投射!
标签: java spring hibernate jpa hql