我想从一个表中选择多行/记录,然后将结果放入一个“变量”中。然后我想打印每一行的内容。
如果我在 Java 中使用 hibernate ,我该怎么做?
例如,我有一个学生表,我想获取该表的所有行。我知道每一行都是表/实体类/bean 的一个实例。 (假设我有一个实体 class-student )
该表就像(假设我在数据库中有一个包含数据的表):
表名:sutdent
有四列
id, lname, fname, 性别
我记得我可以这样做:
List<student> stlist=HibernateUtil.getSession().createQuery("select*from student").list();
//here I want to print the lname of the first row/object
System.out.println(stlist.get(0).getLname(););
为什么我收到错误消息“unexpectesd token *”?
我不能使用 * ?如果我不能使用 *,如果我想获取记录的所有内容(所有属性/列),我该怎么办?
还是有其他错误?我该做什么?谢谢!!
最佳答案
You can do it by two ways.
1. HQL query
2. SQL query
1. HQL Query
- you are using hibernate that means you have done mapping to Student table and Student class.
you just need to change following line.
List<student> stlist=HibernateUtil.getSession().createQuery("from student").list();
and you will get all records from Student table.
2. SQL Query
- you can do by providing SQL query
List<Object> stlist=HibernateUtil.getSession().createSQLQuery("select * from student").list();
you will get all records as Object so you need to manually cast to Student.
关于Java hibernate 从表中选择多行并将结果分配到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15352706/