Baadshah
Baadshah

Reputation: 63

Issue using Java

I have a DAO java class. In the DAO, I execute a native SQL Query which outputs two records from the database. The results is printed on the console. However, when the method is called, only one record is returned. Why?

DAO Java Class:

public Showroom SearchShowroom(String carMake){ 

    Session session = sessionFactory.openSession(); 
    Transaction tx = session.beginTransaction();
    SQLQuery query =  session.createSQLQuery("SELECT * from showroom);

        tx.commit();
        session.close(); 
    return sw;  
}

Upvotes: 0

Views: 63

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36630

You are only returning the last Showroom object which you create in your loop (and discard all others). If you want to return all of them, add them to a List and return that List as the result:

public List<Showroom> SearchShowroom(String carMake){ 
    ...
    List<Showroom> allResult = new ArrayList<>();
    for(Object[] data : result){
        Showroom sw = new Showroom();
        ...
        allResult.add(sw);
    }
    ...

    return allResult;  
}

Besides that immediate fix to your question, please also consider the comments from @borjab. Especially, never use string concatenation to inject variables into SQL statements - always use bind variables. See What is SQL injection? for more information.

Upvotes: 3

Related Questions