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;
}
-
Comment 1: Why do you commit a readonly transaction?borjab– borjab2016年02月01日 11:55:49 +00:00Commented Feb 1, 2016 at 11:55
-
Comment 2: Do not use string concatenation for SQL Queries use parameters. You are opening your code to SQL injections.borjab– borjab2016年02月01日 11:56:33 +00:00Commented Feb 1, 2016 at 11:56
-
Comment 3: Are you using Spring? If this is the case you might be better using the Spring @Transactional annotation in a service. This way you have the flexibility to combina calls to DAOs in a big transaction when you need. And you can separate the transactional scope from the operationborjab– borjab2016年02月01日 11:58:38 +00:00Commented Feb 1, 2016 at 11:58
-
I am not using Spring. Its for learning purposes !Baadshah– Baadshah2016年02月01日 12:04:35 +00:00Commented Feb 1, 2016 at 12:04
-
Then, Baadshah, you may prefer to use it this way. There is a Transactional annotation not related to Spring. But this is just throw away code so you are OK javaee-spec.java.net/nonav/javadocs/javax/transaction/…borjab– borjab2016年02月01日 12:16:47 +00:00Commented Feb 1, 2016 at 12:16
1 Answer 1
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.
8 Comments
public List<Showroom> find() throws Exception{ ShowroomManager sm = new ShowroomManager(); return sm.SearchShowroom(make1); }