Reputation: 2475
I want to know what is the correct way to return resultset in form of some Collection. Or should I create class instances of same class and then return it (how to do that ?) What is the common practice to do this? Or should I learn Hibernate and implement that?
public class Author {
private String table_name = "authors";
int id;
String full_name;
String location;
int age;
String details;
/** Getter Setter Methods here ....*/
/** Constructor here.... */
/* Returns all Authors */
public ArrayList all() {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
/* TODO : figure out which collection is suitable .*/
DbHelper dbHelper = new DbHelper();
Connection conn = dbHelper.getConnection();
ResultSet rs = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
String query = "SELECT * FROM authors";
rs = stmt.executeQuery(query);
while (rs.next()) {
HashMap<String, String> hashmap = new HashMap<>();
int id = rs.getInt(1);
hashmap.put("id",rs.getString(1));
hashmap.put("full_name", rs.getString(2));
hashmap.put("location", rs.getString(3));
hashmap.put("age", rs.getString(4));
hashmap.put("details", rs.getString(5));
list.add(id,hashmap);
//hashmap.clear();
}
} catch (SQLException ex) {
Logger.getLogger(Author.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("you are fuckt");
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Author.class.getName()).log(Level.SEVERE, null, ex);
}
}
return list;
}
}
Upvotes: 2
Views: 659
Reputation: 1842
I would say you should go for hibernate. you will get the list of objects just by performing "list()" method.
code for your reference
List<Authors> al = this.sessionFactory.getCurrentSession().createQuery("from Authors").list();
Hibernare provides many other advantages too. Its definitely better option than JDBC.
JDBC alternative:
best practices says that u should return a DTO(Data transfer object) from DAO layer because it is advisable to get the relevant data in one go from DB so u can minimize the DB hits. Follow This:
List<YourDTO> al = new ArrayList<yourDTO>();
YourDTO is:
class YourDTO
{
private int id:
private Authors authors;
// getters and setters
}
read the data from resultSet as your doing then create the objects of Authors , set the fields , add them to ArrayList with id.
Upvotes: 2
Reputation: 153700
There are many good options available:
Try Spring JDBC first and if that's not enough than invest your time and effort into Hibernate.
Upvotes: 1