我是 Hibernate 的新手,我正在尝试从数据库中获取一些数据。我不想获得完整的数据,而是一个实体的投影。
问题是,在 for 循环中,当我获得投影的 id 和名称时,它会获得默认值 id=0 和 name=null 而不是 id=7 和 name="Name 8" 的记录数据库中的原始实体。你知道是什么导致了这个问题吗?for 循环在最后一个代码中。
这是学生实体
@Entity(name = "Students")
public class Student {
@Id
@GeneratedValue
@Column(name = "StudentId")
private int id;
@Column(name = "Name", nullable = false, length = 50)
private String name;
@Column(name = "Grade")
private Double grade = null;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "FacultyId", nullable = false)
private Faculty faculty;
@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(
joinColumns = @JoinColumn(name = "StudentId"),
inverseJoinColumns = @JoinColumn(name = "CourseId"))
private Collection<Course> courses;
public Student() {
this.courses = new HashSet<Course>();
}
// Setters and Getters for all fields
}
这是学生模型
public class StudentModel {
private int id;
private String name;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
我正在执行的代码
Session session = sessionFactory.openSession();
session.beginTransaction();
{
Criteria criteria = session.createCriteria(Student.class);
criteria.add(Restrictions.eq("name", "Name 8"))
.setProjection(
Projections.projectionList()
.add(Projections.property("id"))
.add(Projections.property("name")))
.setResultTransformer(
Transformers.aliasToBean(StudentModel.class));
@SuppressWarnings("unchecked")
List<StudentModel> students = criteria.list();
for (StudentModel student : students) {
System.out.println(student.getId());
System.out.println(student.getName());
}
session.getTransaction().commit();
session.close();
}