我使用 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 的设置器
在使用 Transformer 时引用Hibernate 异常 PropertyNotFoundException ,我将查询更改为"select student.id as id,..."
,在Long id
内部StudentDTO
但抛出相同的异常,说 setter not found for 1。
每个属性都给出了 Getter/Setter。请提出更改建议!