我想知道以某种Collection形式返回结果集的正确方法是什么。还是应该创建相同类的类实例,然后将其返回(如何执行此操作?),通常的做法是什么?还是应该学习Hibernate并实现它?
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;
}
}
我想说你应该去冬眠。您只需执行“ list()”方法即可获得对象列表。
代码供您参考
List<Authors> al = this.sessionFactory.getCurrentSession().createQuery("from Authors").list();
Hibernare还提供了许多其他优势。它绝对是比JDBC更好的选择。
JDBC替代:
最佳实践表明,您应该从DAO层返回DTO(数据传输对象),因为建议一次性从数据库中获取相关数据,以便最大程度地减少数据库命中率。遵循此:
List<YourDTO> al = new ArrayList<yourDTO>();
您的DTO是:
class YourDTO
{
private int id:
private Authors authors;
// getters and setters
}
在执行操作时从resultSet读取数据,然后创建Authors的对象,设置字段,并将其添加到ID为ArrayList的对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句