有一个名为leagues
的表,创建为:
CREATE TABLE leagues(id INT NOT NULL AUTO_INCREMENT,lname VARCHAR(255),
season VARCHAR(255),PRIMARY KEY (lname),KEY id(id));
映射hibernate xml
为:
<hibernate-mapping>
<class name="pojo.Leagues" table="leagues">
<id column='lname' name='leaguename' type="string"> </id>
<property column="id" name="id" type="integer" />
<property column="season" name="season" type="string" />
</class>
</hibernate-mapping>
我正在尝试从leagues
表中获取数据,但我无法做到。这是方法:
查询不返回任何内容,代码永远不会进入循环。
public LinkedList<String> getLeagues() {
String hql = "select leaguename from pojo.Leagues";
lnames = new LinkedList<String>();
Configuration configuration = new Configuration().configure();
SessionFactory sessFact = configuration.buildSessionFactory();
Session sess = sessFact.openSession();
Query query = sess.createQuery(hql);
List list = query.list();
System.out.println("Heyyyyyyy:ll");
Iterator i = list.iterator();
while(i.hasNext()) {
System.out.println("Inside while block");
Leagues lname = (Leagues)i.next();
lnames.add(lname.getLeaguename());
}
return lnames;
}
我在哪里弄错了?为什么我无法获取数据?
答案 0 :(得分:1)
您没有从数据库获取任何数据的原因是您正在使用纯SQL查询 &amp;打电话
Query query = sess.createQuery(hql);
根据createQuery()
- Hibernate Doc在HQL上运行。
如果要使用纯SQL查询,则必须使用createSQLQuery()
- Hibernate Doc
String sqlQuery = "select leaguename from pojo.Leagues";
SQLQuery query = sess.createSQLQuery(sqlQuery);
或以HQL格式更改您的查询,如下所示
String hqlQuery = "from pojo.Leagues";