Hibernate中的ResultTransformer返回null

时间:2011-06-21 10:39:10

标签: java hibernate criteria resulttransformer

我正在使用ResultTransformer从实体中仅选择特定属性,只是我不需要实体的所有属性。 但我遇到的问题是房产是“一对多”的。 这是一个简单的例子。

@Entity
@Table(name = "STUDENT")
public class Student
{

private long studentId;
private String studentName;
private List<Phone> studentPhoneNumbers = new ArrayList<Phone>();

@Id
@GeneratedValue
@Column(name = "STUDENT_ID")
public long getStudentId()
{
  return this.studentId;
}
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_PHONE", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "PHONE_ID")})
public List<Phone> getStudentPhoneNumbers()
{
  return this.studentPhoneNumbers;
}
@Column(name = "STUDENT_NAME", nullable = false, length = 100)
public String getStudentName()
{
  return this.studentName;
}

以下是ResultTransformer用于存储所选属性的类。

public class StudentDTO
{
private long m_studentId;
private List<Phone> m_studentPhoneNumbers = new ArrayList<Phone>();
.. 
constructors and getters and setters..

最后是Criteria代码

 Criteria criteria = session.createCriteria(Student.class)
    .setProjection(Projections.projectionList()
      .add(Projections.property("studentId"), "m_studentId")
      .add(Projections.property("studentPhoneNumbers"), "m_studentPhoneNumbers"))
    .setResultTransformer(Transformers.aliasToBean(StudentDTO.class));


  List list = criteria.list();
  StudentDTO p = (StudentDTO) list.get(0);

因此,在我获得StudentDTO对象后,只有studenId可用,studentPhoneNumber为null。 这是否意味着ResultTransformer不适用于任何关系?或者我的方式是错的 有什么建议吗?

由于

1 个答案:

答案 0 :(得分:2)

之前我遇到过这个问题。冬眠中的变形金刚通常会导致挫败感。您可以按照建议进行手动分配,也可以使用hibernate将DTO类映射到同一个表。只需将相同的注释添加到StudentDTO类作为Student类,然后像平常一样加载它。因此学生DTO将是:

@Entity
@Table(name = "STUDENT")

public class StudentDTO
{

private long studentId;
private String studentName;
private List<Phone> studentPhoneNumbers = new ArrayList<Phone>();

@Id
@GeneratedValue
@Column(name = "STUDENT_ID")
public long getStudentId()
{
  return this.studentId;
}
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_PHONE", joinColumns = {@JoinColumn(name = "STUDENT_ID")}, inverseJoinColumns = {@JoinColumn(name = "PHONE_ID")})
public List<Phone> getStudentPhoneNumbers()
{
  return this.studentPhoneNumbers;
}

请忽略您不想加载的内容。