【发布时间】:2013-09-15 16:10:19
【问题描述】:
我使用 HQL 从表中仅获取选定的属性,维护非实体类对象的列表。 例如。我的实体类:
@Entity
@Table(name="STUDENT")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(name="NAME", columnDefinition="TEXT", length="60", nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "Dept_id", nullable = false)
private Department department;
// Other fields...
// Getter-Setters
}
并且非持久性 DTO 类只有更少的类成员(例如,仅名称):
public class StudentDTO {
private String name;
// Getter-Setter for name
}
现在使用
public List<StudentDTO> getStudents(Long deptId) {
List<StudentDTO> students;
Query query = session.createQuery("select student.name " +
"from Student as student " +
"where Dept_id =?").setResultTransformer(new AliasToBeanResultTransformer(StudentDTO.class));
query.setString(0, Long.toString(deptId));
students = CommonUtil.castList(StudentDTO.class, query.list());
return students;
}
castList 将任何集合转换为 ArrayList。
public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
List<T> resultList = new ArrayList<T>(c.size());
for(Object o: c)
resultList.add(clazz.cast(o));
return resultList;
}
抛出 org.hibernate.PropertyNotFoundException:在类 ../StudentDTO 上找不到 0 的设置器
参考Hibernate exception PropertyNotFoundException when using Transformer,我将查询更改为"select student.id as id,...",在StudentDTO 中包含Long id,但抛出相同的异常,说找不到1 的setter。
为每个属性提供了Getter/Setter。请提出更改建议!
【问题讨论】:
-
明显的问题是缺少别名。尝试“选择 student.name 作为名称”
-
另外,你能发布完整的堆栈吗?