0

Am using hibernate query to select group of data from the table. Result set of the select query is stored in to List. Query is executing correctly. Even if the query return a empty selection how can i check the List is empty or not..Based on the condition the transaction get executed.

How can i check List is empty or not?

public String getData(String ID){
    Transaction transaction=null;
    Session session=HibernateUtil.getSessionFactory().openSession();
    List<MyClass> myList=null;
    try{
        transaction=session.beginTransaction();
        myList=session.createQuery("from table as t where t.ID=:ID")
                .setString("ID",ID).list();
                transaction.commit();
    }catch(RuntimeException e){
        if(transaction!=null){
            log.error(e);
            transaction.rollback();
        }
    }finally{
        session.flush();
        session.close();
    }

}

3 Answers 3

1

How can i check List is empty or not?

Use isEmpty method.

if(myList.isEmpty()){
// List is empty.
}
1

There is a function to check whether list contains records or not called isEmpty()

myList.isEmpty(); //return booleans based on your myList.

Have a look at this doc.

1
`Based on the condition the transaction get executed.`

if Your transaction executed successfully then only you will get the List as empty otherwise your list will be null because you have initialised it with null

So if the transaction is completed then you can use the isEmpty() or the list.size() method to check the size

List<MyClass> myList=null; **// initialised as null**
try{
    transaction=session.beginTransaction();
    myList=session.createQuery("from table as t where t.ID=:ID")
            .setString("ID",ID).list();
            transaction.commit(); **// if any exception comes myList will be null**
}catch(RuntimeException e){
    if(transaction!=null){
        log.error(e);
        transaction.rollback();
    }
}finally{
    session.flush();
    session.close();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.