简体   繁体   中英

Accessing elements from arraylist returned from method

I am writing code for a webapp that runs a bowling game. The players scores are saved in a database, so that the top ten can be retrieved to be seen on the homepage. Problem is, I cant access the values in the arraylist that is returned from the method that retrieves the scores from the database.

This is a JUnit test method: (CDR is the top player, should assert to true)

<!-- language: c# -->
public class DatabaseTest {
ScoreDB sdbTest = new ScoreDB();
@Test
public void testTopPl(){
    assertTrue(sdbTest.listTopPlayers().get(0).getName() == "CDR");
    }
}

And this is the database retrieval code:

public List<Player> listTopPlayers( ){
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Player> topPlayers = new ArrayList<Player>();

        try {
            trns = session.beginTransaction();
            List<Player> players = session.createQuery("FROM Player").list();

            Collections.sort(players, new ScoreComparator());               

            for (int i=0; i<10; i++){
                topPlayers.add(players.get(i));
            }
            // System.out.print(topPlayers.get(0).getName() + " test");

            trns.commit();
            trns = session.beginTransaction();
          }catch (RuntimeException e) {
              if(trns != null){
                  trns.rollback();
               }
              e.printStackTrace();
              } finally{
                session.flush();
                session.close();
            }
        return topPlayers; 
    }
}

First of all you should use order by in the database and setMaxResults in your query to only retrive the top 10. Otherwise you may have memory problems.

Second you are calling begin transaction twice. Do it only once, besides, you are in a read only operation that doesn't neeed a transaction.

Finnaly post your problem, are you getting some null pointer or detached entitity exception? If you are getting detatched entity use Hibernate.initialize in the property that you are reading.

And of course, use EQUALS to compare String. This might be your real problem. Never compare Strings in Java using "==" operator.

Hope these tips would be usefull.

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