[英]Processing hibernate query result
I've been following this tutorial here The code from the tutorial was : 我在这里一直关注本教程,该教程中的代码为:
private void displayResult(List resultList) {
Vector<String> tableHeaders = new Vector<String>();
Vector tableData = new Vector();
tableHeaders.add("ActorId");
tableHeaders.add("FirstName");
tableHeaders.add("LastName");
tableHeaders.add("LastUpdated");
for(Object o : resultList) {
Actor actor = (Actor)o;
Vector<Object> oneRow = new Vector<Object>();
oneRow.add(actor.getActorId());
oneRow.add(actor.getFirstName());
oneRow.add(actor.getLastName());
oneRow.add(actor.getLastUpdate());
tableData.add(oneRow);
}
resultTable.setModel(new DefaultTableModel(tableData, tableHeaders));
} }
I don't understand why I can't manage to cast my Forfait forfait into (Forfait)o in my for loop. 我不明白为什么我无法在for循环中将我的Forfait Forfait转换为(Forfait)o。 The exception is "java.lang.ClassCastException: java.lang.String cannot be cast to hibernate.util.Forfait"
例外是“ java.lang.ClassCastException:无法将java.lang.String强制转换为hibernate.util.Forfait”
Thanks for your help 谢谢你的帮助
public String[] getAllForfait() {
String query = "SELECT distinct forfait.forfaitNom FROM Forfait forfait";
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery(query);
List resultList = q.list();
session.getTransaction().commit();
String[] Forfaits = {};
int i = 0;
for(Object o : resultList) {
Forfait forfait = (Forfait)o;
Forfaits[i] = forfait.getForfaitNom();
i++;
}
return Forfaits;
}
Your query is selecting just the name (string?) from the table: 您的查询仅从表中选择名称(字符串?):
String query = "SELECT distinct forfait.forfaitNom FROM Forfait forfait";
What you want to do it return everything, so try: 您想要执行的操作将返回所有内容,因此请尝试:
String query "from Forfait"
instead. 代替。 This will return the full object/table instead of just a column from it.
这将返回完整的对象/表,而不是仅返回其中的一列。
If you need to keep the query the same, and are only looking for the name, then change your for loop to the following: 如果您需要保持查询不变,并且仅在查找名称,则将for循环更改为以下内容:
for(Object o : resultList) {
Forfaits[i] = (String)o;
i++;
}
You are only selecting names in your select statement, so resultList will be a list of String
s 您仅在select语句中选择名称,因此resultList将是
String
的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.