我想要一个Criteria查询来使用AliasToBeanResultTransformer实例化一个DTO类.目标是生成一个轻量级分页列表,其中包含用于主页进一步操作的ID.这需要报告类型查询.
Criteria crit = session.createCriteria(Profile.class);
crit.createAlias("personalData", "pd");
crit.createAlias("emails", "e");
crit.createAlias("telephones", "t");
ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("id").as( "id"));
properties.add(Projections.property("pd.lastName").as("lastName"));
properties.add(Projections.property("pd.fullName").as("fullName"));
properties.add(Projections.property("e.emailAddress").as("email"));
properties.add(Projections.property("t.phoneNumber").as("phone"));
crit.setProjection(properties);
crit.setResultTransformer(new AliasToBeanResultTransformer(ProfileDTO.class));
profiles = crit.list();
Run Code Online (Sandbox Code Playgroud)
这无法实例化我的DTO类.ProfileDTO有一个匹配的构造函数:
public ProfileDTO(Long id, String lastName, String fullName, String email,
String phone) {
this(id,fullName);
this.lastName = lastName;
this.email = email;
this.phone = phone;
}
Run Code Online (Sandbox Code Playgroud)
当我使用结果行手动构造ProfileDTO对象时,查询有效
List<Object[]> rows = crit.list();
for ( Object[] row: rows ) {
ProfileDTO dto = new ProfileDTO();
dto.setId((Long)row[0]);
dto.setLastName((String)row[1]);
dto.setFullName((String)row[2]);
dto.setEmail((String)row[3]);
dto.setPhone((String)row[4]);
profiles.add(dto);
}
Run Code Online (Sandbox Code Playgroud)
我的解决方法工作正常,但似乎没必要.我究竟做错了什么?
该AliasToBeanResultTransformer使用setter方法来填充DTO.如果要使用构造函数来创建bean实例,则需要使用AliasToBeanConstructorResultTransformer.
你的DTO似乎有一个setter用于元组的所有元素,lastName除外.也许这就是问题所在.
也就是说,您的代码是简单,易于维护和可重构的.它不会与AliasToBeanResultTransformer重构.我通常喜欢自己实例化我的DTO,就像你一样.
| 归档时间: |
|
| 查看次数: |
7306 次 |
| 最近记录: |