您的位置:首页 > 编程语言 > Java开发

Spring与Hibernate Dao中操作数据库的另外方式

2008-10-24 13:03 525 查看
// search Person Object
/**
* @param firstname
* @param lastname
* @return
*/
public List searchPerson(final String firstname, final String lastname) {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
List list = new ArrayList();

String sql = " select pid,firstname,lastname from person where firstname like '"
+ firstname
+ "%' and lastname like '"
+ lastname
+ "%' order by lastname;";

PreparedStatement pstmt = null;
Connection conn = null;
ResultSet rs = null;

try {

conn = session.connection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();

while (rs != null && rs.next()) {

String pid = rs.getString(1);
String firstname = rs.getString(2);
String lastname = rs.getString(3);
Person person = new Person();
person.setPid(pid);
person.setFirstname(firstname);
person.setLastname(lastname);

list.add(person);

}

} catch (Exception e) {
log.error(e);
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
log.error(e);
} finally {
try {
if (pstmt != null)
pstmt.close();
} catch (Exception e) {
log.error(e);
}

}
}
return list;
}
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: