3

我正在使用 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 = 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 不适用于任何关系?或者我的方式是错误的有什么建议吗?

谢谢

4

1 回答 1

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;
}

只需省略您不想加载的内容。

于 2011-08-12T15:27:49.950 回答