自定义列表问题

时间:2014-01-26 10:22:59

标签: java hibernate list jdbc

我正在尝试将数据库中的一些数据放入自定义List。类:

public class TopTitles {

    private long count;
    private String title;
    private String url;

    public long getCount() {
        return count;
    }

    public void setCount(long count) {
        this.count = count;
    }

    public String getTitle() {
        return title;

    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getUrl() {
        return url;

    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String toString()
    {
        return count+" "+title+" "+url;
    }
}

方法:

public List<TopTitles> getTopTitlesRating() {
        Session session = null;

        session = this.sessionFactory.getCurrentSession();
        Query query = session
                .createSQLQuery("SELECT COUNT(title),title,url FROM SpyPath WHERE title!='Main page' GROUP BY title ORDER BY COUNT(title) DESC LIMIT 0, 10;");

        List<TopTitles> result = query.list();
        return result;
    }

似乎没问题,但是当我试图

List<TopTitles> topTitlesList = spyPathService.getTopTitlesRating();
        System.out.println(topTitlesList.get(0).getTitle());

显示

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to net.babobka.blog.domain.TopTitles

怎么了?

UPD:

这就是我改变方法的方法:

public List<TopTitles> getTopTitlesRating() {
        Session session = null;

        session = this.sessionFactory.getCurrentSession();
        Query query = session
                .createSQLQuery("SELECT COUNT(title),title,url FROM SpyPath WHERE title!='Main page' GROUP BY title ORDER BY COUNT(title) DESC LIMIT 0, 10;");

        List<?> result = query.list();
        List<TopTitles> list = new ArrayList<TopTitles>();
        for(Object o : result) {
            list.add((TopTitles)o);
        }
        return list;
    }

仍然没有工作/

1 个答案:

答案 0 :(得分:1)

Hibernate从Query.list

返回一个原始List
List<TopTitles> list = new ArrayList<TopTitles>();
for(Object o : result) {
    list.add((TopTitles)o);
}

使用此列表进行迭代