我是hibernate的新手,并且正在努力为标准查询添加单个投影。我收到以下代码的错误:" java.lang.Integer无法转换为[Ljava.lang.Object,在第29行。我知道这很简单,但我无法弄清楚我是什么在这里做错了!
代码如下:
package com.simpleprogrammer;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class Program {
public static void main(String[] args) {
System.out.println(org.hibernate.Version.getVersionString());
System.out.println("Creating session!");
PopulateSampleData();
Session session = HibernateUtilities.getSessionFactory().openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.eq("name", "Joe")).setProjection(Projections.property("id"));
List<Object[]> results = criteria.list();
for(Object[] result : results) {
for (Object o : result)
System.out.println("Name is " + o.toString());
}
session.close();
HibernateUtilities.getSessionFactory().close();
}
private static void PopulateSampleData() {
Session session = HibernateUtilities.getSessionFactory().openSession();
session.beginTransaction();
User joe = CreateUser("Joe", 500, 50, "Good job", "You made it!");
session.save(joe);
User bob = CreateUser("Bob", 300, 20, "Taco time!");
session.save(bob);
User amy = CreateUser("Amy", 250, 200, "Yes!!!");
session.save(amy);
session.getTransaction().commit();
session.close();
}
private static User CreateUser(String name, int goal, int total, String... alerts) {
User user = new User();
user.setName(name);
user.getProtienData().setGoal(goal);
user.addHistory(new UserHistory(new Date(), "Set goal to " + goal));
user.getProtienData().setTotal(total);
user.addHistory(new UserHistory(new Date(), "Set total to " + total));
for (String alert : alerts) {
user.getGoalAlerts().add(new GoalAlert(alert));
}
return user;
}
}
答案 0 :(得分:0)
我怀疑criteria.list()
正在返回List<Integer>
而不是List<Object[]>
,因为提取了一列。
尝试更改
List<Object[]> results = criteria.list();
到
List<Integer> results = criteria.list();