我需要一些帮助我对hibernate有新功能我已经使用内连接加入了三个表,这些表都有一对一映射我在列表中得到结果但是,如何迭代该列表。我试过使用迭代器,但没有任何帮助,请在这里帮助我是代码片段。
@Entity
public class Laptop {
@Id
private int lid;
private String lname;
//getters and setter
@Entity
public class Validity{
@Id
private int lid;
private String validitydate;
//getters and setter
@Entity
public class Student {
@Id
private int lid;
private int rollno;
private String name;
private int marks;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name="lid")
private Laptop laptop;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="lid")
private Validity validity;
//getters and setters
查询我正在解雇
String hql = "Select s from Student s inner join s.laptop left join
s.validity where s.lid = 1 and s.marks = 45";
Query query = session.createQuery(hql);
List<Object[]> list = query.list();
Iterator it = list.iterator();
Object[] obj = list.toArray();
while(it.hasNext())
{
Object ob = (Object)it.next();
Student s = (Student)ob;
System.out.println("Student id is "+s.getLid());
Laptop l = (Laptop)ob; // gives me error here cannot cast laptop to
student
System.out.println("laptop id is "+l.getLid());
System.out.println("laptop name is "+l.getLname());
}
答案 0 :(得分:1)
您的查询是
Select s from Student s where ...
因此它选择了学生的实例。
结果是List<Student>
,而不是List<Object[]>
。
使用正确的类型,并使用类型化查询:
Query<Student> query = session.createQuery(hql, Student.class);
List<Student> list = query.list();
for (Student student : list) {
...
}
答案 1 :(得分:0)
Iterator it = list.iterator();
Object[] obj = list.toArray();
while(it.hasNext())
{
Object ob = (Object)it.next();
Student s = (Student)ob;
System.out.println("Student id is "+s.getLid());
Laptop l = s.getLaptop();
System.out.println("laptop id is "+l.getLid());
System.out.println("laptop name is "+l.getLname());
Validity v = s.getValidity();
System.out.println("Validity id is "+v.getLid());
System.out.println("Validity Date is "+v.getValiditydate());
}