2016-03-16 64 views
0

我是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

你能指出你在哪裏得到錯誤?第29行指向右大括號:for(Object [] result:results){Object o:result) System.out.println(「Name is」+ o.toString()); } //第29行 – Sanj

回答

0

我懷疑criteria.list()正在返回List<Integer>而不是List<Object[]>,因爲一列是牽強 嘗試改變

List<Object[]> results = criteria.list(); 

List<Integer> results = criteria.list(); 
+0

但問題在於我無法循環訪問一組Integer對象。如果我將for語句改爲for(Integer result:results){它會拋出一個錯誤? – user6074035

+0

你得到的例外是什麼? – Sanj