简体   繁体   中英

SetMaxResults() Not Working In Hibernate

i am newbie in Hibernate and getting some errors using the SetMaxResults() function. This is my MySQL table data::

1   J. C. Smell
2   J. C. Smell
3   J. C. Smell
4   J. C. Smell

This is the method to retrieve one record from 4 identical records.

private Person findPerson(Session session, String name){
        Query query = session.createQuery("from Person p where p.name=:name");
        query.setParameter("name", name);
        query.setMaxResults(1);
        Person person = (Person)query.list();
        if(person == null)
            return null;
        return person;
    }

I expect to get one record but according to the Exception am getting an ArrayList of records. The exception comes from this line Person person = (Person)query.list(); That line has the number 34 in my source code.This is the exception.

java.lang.ClassCastException: java.util.ArrayList cannot be cast to chapter3.simple.Person
    at chapter3.simple.RankingTest.findPerson(RankingTest.java:34)
    at chapter3.simple.RankingTest.savePerson(RankingTest.java:41)
    at chapter3.simple.RankingTest.testSaveRanking(RankingTest.java:72)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    ...
    ...

What am i doing wrong? thanks

EDIT

Hi, Is the setMaxResults(1) not suppose to return 1 results from the records?

 Person person = (Person)query.list();

That is an illegal cast. Though the list have a single element, you cannot magically cast a list to Person . When you set max result, it still returns a list with 1 element.

Hence you have to do

Person person = (Person)query.list().get(0);

Better use

Person person = (Person)query.uniqueResult();

But be careful with this, it throws exception if there is not unique entry.

But it your case use

Person person = (Person)query.list().get(0);

Just change your code like this, i hope it will work. Thanks

private Person findPerson(Session session, String name){
        Query query = session.createQuery("from Person p where p.name=:name")
        query.setParameter("name", name)
        query.setMaxResults(1);
        return (Person)query.uniqueResult();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM